Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67        parent: a reference to the parent expression (or None, in case of root expressions).
  68        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  69            uses to refer to it.
  70        comments: a list of comments that are associated with a given expression. This is used in
  71            order to preserve comments when transpiling SQL code.
  72        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  73            optimizer, in order to enable some transformations that require type information.
  74
  75    Example:
  76        >>> class Foo(Expression):
  77        ...     arg_types = {"this": True, "expression": False}
  78
  79        The above definition informs us that Foo is an Expression that requires an argument called
  80        "this" and may also optionally receive an argument called "expression".
  81
  82    Args:
  83        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 262        if self.comments is None:
 263            self.comments = []
 264        if comments:
 265            self.comments.extend(comments)
 266
 267    def append(self, arg_key, value):
 268        """
 269        Appends value to arg_key if it's a list or sets it as a new list.
 270
 271        Args:
 272            arg_key (str): name of the list expression arg
 273            value (Any): value to append to the list
 274        """
 275        if not isinstance(self.args.get(arg_key), list):
 276            self.args[arg_key] = []
 277        self.args[arg_key].append(value)
 278        self._set_parent(arg_key, value)
 279
 280    def set(self, arg_key, value):
 281        """
 282        Sets `arg_key` to `value`.
 283
 284        Args:
 285            arg_key (str): name of the expression arg.
 286            value: value to set the arg to.
 287        """
 288        self.args[arg_key] = value
 289        self._set_parent(arg_key, value)
 290
 291    def _set_parent(self, arg_key, value):
 292        if hasattr(value, "parent"):
 293            value.parent = self
 294            value.arg_key = arg_key
 295        elif type(value) is list:
 296            for v in value:
 297                if hasattr(v, "parent"):
 298                    v.parent = self
 299                    v.arg_key = arg_key
 300
 301    @property
 302    def depth(self):
 303        """
 304        Returns the depth of this tree.
 305        """
 306        if self.parent:
 307            return self.parent.depth + 1
 308        return 0
 309
 310    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 311        """Yields the key and expression for all arguments, exploding list args."""
 312        for k, vs in self.args.items():
 313            if type(vs) is list:
 314                for v in vs:
 315                    if hasattr(v, "parent"):
 316                        yield k, v
 317            else:
 318                if hasattr(vs, "parent"):
 319                    yield k, vs
 320
 321    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 322        """
 323        Returns the first node in this tree which matches at least one of
 324        the specified types.
 325
 326        Args:
 327            expression_types: the expression type(s) to match.
 328
 329        Returns:
 330            The node which matches the criteria or None if no such node was found.
 331        """
 332        return next(self.find_all(*expression_types, bfs=bfs), None)
 333
 334    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 335        """
 336        Returns a generator object which visits all nodes in this tree and only
 337        yields those that match at least one of the specified expression types.
 338
 339        Args:
 340            expression_types: the expression type(s) to match.
 341
 342        Returns:
 343            The generator object.
 344        """
 345        for expression, *_ in self.walk(bfs=bfs):
 346            if isinstance(expression, expression_types):
 347                yield expression
 348
 349    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 350        """
 351        Returns a nearest parent matching expression_types.
 352
 353        Args:
 354            expression_types: the expression type(s) to match.
 355
 356        Returns:
 357            The parent node.
 358        """
 359        ancestor = self.parent
 360        while ancestor and not isinstance(ancestor, expression_types):
 361            ancestor = ancestor.parent
 362        return t.cast(E, ancestor)
 363
 364    @property
 365    def parent_select(self):
 366        """
 367        Returns the parent select statement.
 368        """
 369        return self.find_ancestor(Select)
 370
 371    @property
 372    def same_parent(self):
 373        """Returns if the parent is the same class as itself."""
 374        return type(self.parent) is self.__class__
 375
 376    def root(self) -> Expression:
 377        """
 378        Returns the root expression of this tree.
 379        """
 380        expression = self
 381        while expression.parent:
 382            expression = expression.parent
 383        return expression
 384
 385    def walk(self, bfs=True, prune=None):
 386        """
 387        Returns a generator object which visits all nodes in this tree.
 388
 389        Args:
 390            bfs (bool): if set to True the BFS traversal order will be applied,
 391                otherwise the DFS traversal will be used instead.
 392            prune ((node, parent, arg_key) -> bool): callable that returns True if
 393                the generator should stop traversing this branch of the tree.
 394
 395        Returns:
 396            the generator object.
 397        """
 398        if bfs:
 399            yield from self.bfs(prune=prune)
 400        else:
 401            yield from self.dfs(prune=prune)
 402
 403    def dfs(self, parent=None, key=None, prune=None):
 404        """
 405        Returns a generator object which visits all nodes in this tree in
 406        the DFS (Depth-first) order.
 407
 408        Returns:
 409            The generator object.
 410        """
 411        parent = parent or self.parent
 412        yield self, parent, key
 413        if prune and prune(self, parent, key):
 414            return
 415
 416        for k, v in self.iter_expressions():
 417            yield from v.dfs(self, k, prune)
 418
 419    def bfs(self, prune=None):
 420        """
 421        Returns a generator object which visits all nodes in this tree in
 422        the BFS (Breadth-first) order.
 423
 424        Returns:
 425            The generator object.
 426        """
 427        queue = deque([(self, self.parent, None)])
 428
 429        while queue:
 430            item, parent, key = queue.popleft()
 431
 432            yield item, parent, key
 433            if prune and prune(item, parent, key):
 434                continue
 435
 436            for k, v in item.iter_expressions():
 437                queue.append((v, item, k))
 438
 439    def unnest(self):
 440        """
 441        Returns the first non parenthesis child or self.
 442        """
 443        expression = self
 444        while type(expression) is Paren:
 445            expression = expression.this
 446        return expression
 447
 448    def unalias(self):
 449        """
 450        Returns the inner expression if this is an Alias.
 451        """
 452        if isinstance(self, Alias):
 453            return self.this
 454        return self
 455
 456    def unnest_operands(self):
 457        """
 458        Returns unnested operands as a tuple.
 459        """
 460        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 461
 462    def flatten(self, unnest=True):
 463        """
 464        Returns a generator which yields child nodes who's parents are the same class.
 465
 466        A AND B AND C -> [A, B, C]
 467        """
 468        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 469            if not type(node) is self.__class__:
 470                yield node.unnest() if unnest else node
 471
 472    def __str__(self):
 473        return self.sql()
 474
 475    def __repr__(self):
 476        return self._to_s()
 477
 478    def sql(self, dialect: DialectType = None, **opts) -> str:
 479        """
 480        Returns SQL string representation of this tree.
 481
 482        Args:
 483            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 484            opts: other `sqlglot.generator.Generator` options.
 485
 486        Returns:
 487            The SQL string.
 488        """
 489        from sqlglot.dialects import Dialect
 490
 491        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 492
 493    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 494        indent = "" if not level else "\n"
 495        indent += "".join(["  "] * level)
 496        left = f"({self.key.upper()} "
 497
 498        args: t.Dict[str, t.Any] = {
 499            k: ", ".join(
 500                v._to_s(hide_missing=hide_missing, level=level + 1)
 501                if hasattr(v, "_to_s")
 502                else str(v)
 503                for v in ensure_list(vs)
 504                if v is not None
 505            )
 506            for k, vs in self.args.items()
 507        }
 508        args["comments"] = self.comments
 509        args["type"] = self.type
 510        args = {k: v for k, v in args.items() if v or not hide_missing}
 511
 512        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 513        right += ")"
 514
 515        return indent + left + right
 516
 517    def transform(self, fun, *args, copy=True, **kwargs):
 518        """
 519        Recursively visits all tree nodes (excluding already transformed ones)
 520        and applies the given transformation function to each node.
 521
 522        Args:
 523            fun (function): a function which takes a node as an argument and returns a
 524                new transformed node or the same node without modifications. If the function
 525                returns None, then the corresponding node will be removed from the syntax tree.
 526            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 527                modified in place.
 528
 529        Returns:
 530            The transformed tree.
 531        """
 532        node = self.copy() if copy else self
 533        new_node = fun(node, *args, **kwargs)
 534
 535        if new_node is None or not isinstance(new_node, Expression):
 536            return new_node
 537        if new_node is not node:
 538            new_node.parent = node.parent
 539            return new_node
 540
 541        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 542        return new_node
 543
 544    def replace(self, expression):
 545        """
 546        Swap out this expression with a new expression.
 547
 548        For example::
 549
 550            >>> tree = Select().select("x").from_("tbl")
 551            >>> tree.find(Column).replace(Column(this="y"))
 552            (COLUMN this: y)
 553            >>> tree.sql()
 554            'SELECT y FROM tbl'
 555
 556        Args:
 557            expression (Expression|None): new node
 558
 559        Returns:
 560            The new expression or expressions.
 561        """
 562        if not self.parent:
 563            return expression
 564
 565        parent = self.parent
 566        self.parent = None
 567
 568        replace_children(parent, lambda child: expression if child is self else child)
 569        return expression
 570
 571    def pop(self):
 572        """
 573        Remove this expression from its AST.
 574
 575        Returns:
 576            The popped expression.
 577        """
 578        self.replace(None)
 579        return self
 580
 581    def assert_is(self, type_):
 582        """
 583        Assert that this `Expression` is an instance of `type_`.
 584
 585        If it is NOT an instance of `type_`, this raises an assertion error.
 586        Otherwise, this returns this expression.
 587
 588        Examples:
 589            This is useful for type security in chained expressions:
 590
 591            >>> import sqlglot
 592            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 593            'SELECT x, z FROM y'
 594        """
 595        assert isinstance(self, type_)
 596        return self
 597
 598    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 599        """
 600        Checks if this expression is valid (e.g. all mandatory args are set).
 601
 602        Args:
 603            args: a sequence of values that were used to instantiate a Func expression. This is used
 604                to check that the provided arguments don't exceed the function argument limit.
 605
 606        Returns:
 607            A list of error messages for all possible errors that were found.
 608        """
 609        errors: t.List[str] = []
 610
 611        for k in self.args:
 612            if k not in self.arg_types:
 613                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 614        for k, mandatory in self.arg_types.items():
 615            v = self.args.get(k)
 616            if mandatory and (v is None or (isinstance(v, list) and not v)):
 617                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 618
 619        if (
 620            args
 621            and isinstance(self, Func)
 622            and len(args) > len(self.arg_types)
 623            and not self.is_var_len_args
 624        ):
 625            errors.append(
 626                f"The number of provided arguments ({len(args)}) is greater than "
 627                f"the maximum number of supported arguments ({len(self.arg_types)})"
 628            )
 629
 630        return errors
 631
 632    def dump(self):
 633        """
 634        Dump this Expression to a JSON-serializable dict.
 635        """
 636        from sqlglot.serde import dump
 637
 638        return dump(self)
 639
 640    @classmethod
 641    def load(cls, obj):
 642        """
 643        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 644        """
 645        from sqlglot.serde import load
 646
 647        return load(obj)
 648
 649
 650IntoType = t.Union[
 651    str,
 652    t.Type[Expression],
 653    t.Collection[t.Union[str, t.Type[Expression]]],
 654]
 655ExpOrStr = t.Union[str, Expression]
 656
 657
 658class Condition(Expression):
 659    def and_(self, *expressions, dialect=None, copy=True, **opts):
 660        """
 661        AND this condition with one or multiple expressions.
 662
 663        Example:
 664            >>> condition("x=1").and_("y=1").sql()
 665            'x = 1 AND y = 1'
 666
 667        Args:
 668            *expressions (str | Expression): the SQL code strings to parse.
 669                If an `Expression` instance is passed, it will be used as-is.
 670            dialect (str): the dialect used to parse the input expression.
 671            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
 672            opts (kwargs): other options to use to parse the input expressions.
 673
 674        Returns:
 675            And: the new condition.
 676        """
 677        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 678
 679    def or_(self, *expressions, dialect=None, copy=True, **opts):
 680        """
 681        OR this condition with one or multiple expressions.
 682
 683        Example:
 684            >>> condition("x=1").or_("y=1").sql()
 685            'x = 1 OR y = 1'
 686
 687        Args:
 688            *expressions (str | Expression): the SQL code strings to parse.
 689                If an `Expression` instance is passed, it will be used as-is.
 690            dialect (str): the dialect used to parse the input expression.
 691            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
 692            opts (kwargs): other options to use to parse the input expressions.
 693
 694        Returns:
 695            Or: the new condition.
 696        """
 697        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 698
 699    def not_(self, copy=True):
 700        """
 701        Wrap this condition with NOT.
 702
 703        Example:
 704            >>> condition("x=1").not_().sql()
 705            'NOT x = 1'
 706
 707        Args:
 708            copy (bool): whether or not to copy this object.
 709
 710        Returns:
 711            Not: the new condition.
 712        """
 713        return not_(self, copy=copy)
 714
 715    def _binop(self, klass: t.Type[E], other: ExpOrStr, reverse=False) -> E:
 716        this = self.copy()
 717        other = convert(other, copy=True)
 718        if not isinstance(this, klass) and not isinstance(other, klass):
 719            this = _wrap(this, Binary)
 720            other = _wrap(other, Binary)
 721        if reverse:
 722            return klass(this=other, expression=this)
 723        return klass(this=this, expression=other)
 724
 725    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 726        return Bracket(
 727            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 728        )
 729
 730    def isin(
 731        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
 732    ) -> In:
 733        return In(
 734            this=_maybe_copy(self, copy),
 735            expressions=[convert(e, copy=copy) for e in expressions],
 736            query=maybe_parse(query, copy=copy, **opts) if query else None,
 737        )
 738
 739    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
 740        return Between(
 741            this=_maybe_copy(self, copy),
 742            low=convert(low, copy=copy, **opts),
 743            high=convert(high, copy=copy, **opts),
 744        )
 745
 746    def like(self, other: ExpOrStr) -> Like:
 747        return self._binop(Like, other)
 748
 749    def ilike(self, other: ExpOrStr) -> ILike:
 750        return self._binop(ILike, other)
 751
 752    def eq(self, other: ExpOrStr) -> EQ:
 753        return self._binop(EQ, other)
 754
 755    def neq(self, other: ExpOrStr) -> NEQ:
 756        return self._binop(NEQ, other)
 757
 758    def rlike(self, other: ExpOrStr) -> RegexpLike:
 759        return self._binop(RegexpLike, other)
 760
 761    def __lt__(self, other: ExpOrStr) -> LT:
 762        return self._binop(LT, other)
 763
 764    def __le__(self, other: ExpOrStr) -> LTE:
 765        return self._binop(LTE, other)
 766
 767    def __gt__(self, other: ExpOrStr) -> GT:
 768        return self._binop(GT, other)
 769
 770    def __ge__(self, other: ExpOrStr) -> GTE:
 771        return self._binop(GTE, other)
 772
 773    def __add__(self, other: ExpOrStr) -> Add:
 774        return self._binop(Add, other)
 775
 776    def __radd__(self, other: ExpOrStr) -> Add:
 777        return self._binop(Add, other, reverse=True)
 778
 779    def __sub__(self, other: ExpOrStr) -> Sub:
 780        return self._binop(Sub, other)
 781
 782    def __rsub__(self, other: ExpOrStr) -> Sub:
 783        return self._binop(Sub, other, reverse=True)
 784
 785    def __mul__(self, other: ExpOrStr) -> Mul:
 786        return self._binop(Mul, other)
 787
 788    def __rmul__(self, other: ExpOrStr) -> Mul:
 789        return self._binop(Mul, other, reverse=True)
 790
 791    def __truediv__(self, other: ExpOrStr) -> Div:
 792        return self._binop(Div, other)
 793
 794    def __rtruediv__(self, other: ExpOrStr) -> Div:
 795        return self._binop(Div, other, reverse=True)
 796
 797    def __floordiv__(self, other: ExpOrStr) -> IntDiv:
 798        return self._binop(IntDiv, other)
 799
 800    def __rfloordiv__(self, other: ExpOrStr) -> IntDiv:
 801        return self._binop(IntDiv, other, reverse=True)
 802
 803    def __mod__(self, other: ExpOrStr) -> Mod:
 804        return self._binop(Mod, other)
 805
 806    def __rmod__(self, other: ExpOrStr) -> Mod:
 807        return self._binop(Mod, other, reverse=True)
 808
 809    def __pow__(self, other: ExpOrStr) -> Pow:
 810        return self._binop(Pow, other)
 811
 812    def __rpow__(self, other: ExpOrStr) -> Pow:
 813        return self._binop(Pow, other, reverse=True)
 814
 815    def __and__(self, other: ExpOrStr) -> And:
 816        return self._binop(And, other)
 817
 818    def __rand__(self, other: ExpOrStr) -> And:
 819        return self._binop(And, other, reverse=True)
 820
 821    def __or__(self, other: ExpOrStr) -> Or:
 822        return self._binop(Or, other)
 823
 824    def __ror__(self, other: ExpOrStr) -> Or:
 825        return self._binop(Or, other, reverse=True)
 826
 827    def __neg__(self) -> Neg:
 828        return Neg(this=_wrap(self.copy(), Binary))
 829
 830    def __invert__(self) -> Not:
 831        return not_(self.copy())
 832
 833
 834class Predicate(Condition):
 835    """Relationships like x = y, x > 1, x >= y."""
 836
 837
 838class DerivedTable(Expression):
 839    @property
 840    def alias_column_names(self):
 841        table_alias = self.args.get("alias")
 842        if not table_alias:
 843            return []
 844        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 845        return [c.name for c in column_list]
 846
 847    @property
 848    def selects(self):
 849        return self.this.selects if isinstance(self.this, Subqueryable) else []
 850
 851    @property
 852    def named_selects(self):
 853        return [select.output_name for select in self.selects]
 854
 855
 856class Unionable(Expression):
 857    def union(self, expression, distinct=True, dialect=None, **opts):
 858        """
 859        Builds a UNION expression.
 860
 861        Example:
 862            >>> import sqlglot
 863            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 864            'SELECT * FROM foo UNION SELECT * FROM bla'
 865
 866        Args:
 867            expression (str | Expression): the SQL code string.
 868                If an `Expression` instance is passed, it will be used as-is.
 869            distinct (bool): set the DISTINCT flag if and only if this is true.
 870            dialect (str): the dialect used to parse the input expression.
 871            opts (kwargs): other options to use to parse the input expressions.
 872        Returns:
 873            Union: the Union expression.
 874        """
 875        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 876
 877    def intersect(self, expression, distinct=True, dialect=None, **opts):
 878        """
 879        Builds an INTERSECT expression.
 880
 881        Example:
 882            >>> import sqlglot
 883            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 884            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 885
 886        Args:
 887            expression (str | Expression): the SQL code string.
 888                If an `Expression` instance is passed, it will be used as-is.
 889            distinct (bool): set the DISTINCT flag if and only if this is true.
 890            dialect (str): the dialect used to parse the input expression.
 891            opts (kwargs): other options to use to parse the input expressions.
 892        Returns:
 893            Intersect: the Intersect expression
 894        """
 895        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 896
 897    def except_(self, expression, distinct=True, dialect=None, **opts):
 898        """
 899        Builds an EXCEPT expression.
 900
 901        Example:
 902            >>> import sqlglot
 903            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 904            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 905
 906        Args:
 907            expression (str | Expression): the SQL code string.
 908                If an `Expression` instance is passed, it will be used as-is.
 909            distinct (bool): set the DISTINCT flag if and only if this is true.
 910            dialect (str): the dialect used to parse the input expression.
 911            opts (kwargs): other options to use to parse the input expressions.
 912        Returns:
 913            Except: the Except expression
 914        """
 915        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 916
 917
 918class UDTF(DerivedTable, Unionable):
 919    @property
 920    def selects(self):
 921        alias = self.args.get("alias")
 922        return alias.columns if alias else []
 923
 924
 925class Cache(Expression):
 926    arg_types = {
 927        "with": False,
 928        "this": True,
 929        "lazy": False,
 930        "options": False,
 931        "expression": False,
 932    }
 933
 934
 935class Uncache(Expression):
 936    arg_types = {"this": True, "exists": False}
 937
 938
 939class Create(Expression):
 940    arg_types = {
 941        "with": False,
 942        "this": True,
 943        "kind": True,
 944        "expression": False,
 945        "exists": False,
 946        "properties": False,
 947        "replace": False,
 948        "unique": False,
 949        "indexes": False,
 950        "no_schema_binding": False,
 951        "begin": False,
 952    }
 953
 954
 955class Describe(Expression):
 956    arg_types = {"this": True, "kind": False}
 957
 958
 959class Pragma(Expression):
 960    pass
 961
 962
 963class Set(Expression):
 964    arg_types = {"expressions": False}
 965
 966
 967class SetItem(Expression):
 968    arg_types = {
 969        "this": False,
 970        "expressions": False,
 971        "kind": False,
 972        "collate": False,  # MySQL SET NAMES statement
 973        "global": False,
 974    }
 975
 976
 977class Show(Expression):
 978    arg_types = {
 979        "this": True,
 980        "target": False,
 981        "offset": False,
 982        "limit": False,
 983        "like": False,
 984        "where": False,
 985        "db": False,
 986        "full": False,
 987        "mutex": False,
 988        "query": False,
 989        "channel": False,
 990        "global": False,
 991        "log": False,
 992        "position": False,
 993        "types": False,
 994    }
 995
 996
 997class UserDefinedFunction(Expression):
 998    arg_types = {"this": True, "expressions": False, "wrapped": False}
 999
1000
1001class CharacterSet(Expression):
1002    arg_types = {"this": True, "default": False}
1003
1004
1005class With(Expression):
1006    arg_types = {"expressions": True, "recursive": False}
1007
1008    @property
1009    def recursive(self) -> bool:
1010        return bool(self.args.get("recursive"))
1011
1012
1013class WithinGroup(Expression):
1014    arg_types = {"this": True, "expression": False}
1015
1016
1017class CTE(DerivedTable):
1018    arg_types = {"this": True, "alias": True}
1019
1020
1021class TableAlias(Expression):
1022    arg_types = {"this": False, "columns": False}
1023
1024    @property
1025    def columns(self):
1026        return self.args.get("columns") or []
1027
1028
1029class BitString(Condition):
1030    pass
1031
1032
1033class HexString(Condition):
1034    pass
1035
1036
1037class ByteString(Condition):
1038    pass
1039
1040
1041class Column(Condition):
1042    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1043
1044    @property
1045    def table(self) -> str:
1046        return self.text("table")
1047
1048    @property
1049    def db(self) -> str:
1050        return self.text("db")
1051
1052    @property
1053    def catalog(self) -> str:
1054        return self.text("catalog")
1055
1056    @property
1057    def output_name(self) -> str:
1058        return self.name
1059
1060    @property
1061    def parts(self) -> t.List[Identifier]:
1062        """Return the parts of a column in order catalog, db, table, name."""
1063        return [part for part in reversed(list(self.args.values())) if part]
1064
1065    def to_dot(self) -> Dot:
1066        """Converts the column into a dot expression."""
1067        parts = self.parts
1068        parent = self.parent
1069
1070        while parent:
1071            if isinstance(parent, Dot):
1072                parts.append(parent.expression)
1073            parent = parent.parent
1074
1075        return Dot.build(parts)
1076
1077
1078class ColumnPosition(Expression):
1079    arg_types = {"this": False, "position": True}
1080
1081
1082class ColumnDef(Expression):
1083    arg_types = {
1084        "this": True,
1085        "kind": False,
1086        "constraints": False,
1087        "exists": False,
1088        "position": False,
1089    }
1090
1091    @property
1092    def constraints(self) -> t.List[ColumnConstraint]:
1093        return self.args.get("constraints") or []
1094
1095
1096class AlterColumn(Expression):
1097    arg_types = {
1098        "this": True,
1099        "dtype": False,
1100        "collate": False,
1101        "using": False,
1102        "default": False,
1103        "drop": False,
1104    }
1105
1106
1107class RenameTable(Expression):
1108    pass
1109
1110
1111class SetTag(Expression):
1112    arg_types = {"expressions": True, "unset": False}
1113
1114
1115class Comment(Expression):
1116    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1117
1118
1119class ColumnConstraint(Expression):
1120    arg_types = {"this": False, "kind": True}
1121
1122    @property
1123    def kind(self) -> ColumnConstraintKind:
1124        return self.args["kind"]
1125
1126
1127class ColumnConstraintKind(Expression):
1128    pass
1129
1130
1131class AutoIncrementColumnConstraint(ColumnConstraintKind):
1132    pass
1133
1134
1135class CaseSpecificColumnConstraint(ColumnConstraintKind):
1136    arg_types = {"not_": True}
1137
1138
1139class CharacterSetColumnConstraint(ColumnConstraintKind):
1140    arg_types = {"this": True}
1141
1142
1143class CheckColumnConstraint(ColumnConstraintKind):
1144    pass
1145
1146
1147class CollateColumnConstraint(ColumnConstraintKind):
1148    pass
1149
1150
1151class CommentColumnConstraint(ColumnConstraintKind):
1152    pass
1153
1154
1155class CompressColumnConstraint(ColumnConstraintKind):
1156    pass
1157
1158
1159class DateFormatColumnConstraint(ColumnConstraintKind):
1160    arg_types = {"this": True}
1161
1162
1163class DefaultColumnConstraint(ColumnConstraintKind):
1164    pass
1165
1166
1167class EncodeColumnConstraint(ColumnConstraintKind):
1168    pass
1169
1170
1171class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1172    # this: True -> ALWAYS, this: False -> BY DEFAULT
1173    arg_types = {
1174        "this": False,
1175        "start": False,
1176        "increment": False,
1177        "minvalue": False,
1178        "maxvalue": False,
1179        "cycle": False,
1180    }
1181
1182
1183class InlineLengthColumnConstraint(ColumnConstraintKind):
1184    pass
1185
1186
1187class NotNullColumnConstraint(ColumnConstraintKind):
1188    arg_types = {"allow_null": False}
1189
1190
1191# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1192class OnUpdateColumnConstraint(ColumnConstraintKind):
1193    pass
1194
1195
1196class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1197    arg_types = {"desc": False}
1198
1199
1200class TitleColumnConstraint(ColumnConstraintKind):
1201    pass
1202
1203
1204class UniqueColumnConstraint(ColumnConstraintKind):
1205    arg_types: t.Dict[str, t.Any] = {}
1206
1207
1208class UppercaseColumnConstraint(ColumnConstraintKind):
1209    arg_types: t.Dict[str, t.Any] = {}
1210
1211
1212class PathColumnConstraint(ColumnConstraintKind):
1213    pass
1214
1215
1216class Constraint(Expression):
1217    arg_types = {"this": True, "expressions": True}
1218
1219
1220class Delete(Expression):
1221    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1222
1223    def delete(
1224        self,
1225        table: ExpOrStr,
1226        dialect: DialectType = None,
1227        copy: bool = True,
1228        **opts,
1229    ) -> Delete:
1230        """
1231        Create a DELETE expression or replace the table on an existing DELETE expression.
1232
1233        Example:
1234            >>> delete("tbl").sql()
1235            'DELETE FROM tbl'
1236
1237        Args:
1238            table: the table from which to delete.
1239            dialect: the dialect used to parse the input expression.
1240            copy: if `False`, modify this expression instance in-place.
1241            opts: other options to use to parse the input expressions.
1242
1243        Returns:
1244            Delete: the modified expression.
1245        """
1246        return _apply_builder(
1247            expression=table,
1248            instance=self,
1249            arg="this",
1250            dialect=dialect,
1251            into=Table,
1252            copy=copy,
1253            **opts,
1254        )
1255
1256    def where(
1257        self,
1258        *expressions: ExpOrStr,
1259        append: bool = True,
1260        dialect: DialectType = None,
1261        copy: bool = True,
1262        **opts,
1263    ) -> Delete:
1264        """
1265        Append to or set the WHERE expressions.
1266
1267        Example:
1268            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1269            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1270
1271        Args:
1272            *expressions: the SQL code strings to parse.
1273                If an `Expression` instance is passed, it will be used as-is.
1274                Multiple expressions are combined with an AND operator.
1275            append: if `True`, AND the new expressions to any existing expression.
1276                Otherwise, this resets the expression.
1277            dialect: the dialect used to parse the input expressions.
1278            copy: if `False`, modify this expression instance in-place.
1279            opts: other options to use to parse the input expressions.
1280
1281        Returns:
1282            Delete: the modified expression.
1283        """
1284        return _apply_conjunction_builder(
1285            *expressions,
1286            instance=self,
1287            arg="where",
1288            append=append,
1289            into=Where,
1290            dialect=dialect,
1291            copy=copy,
1292            **opts,
1293        )
1294
1295    def returning(
1296        self,
1297        expression: ExpOrStr,
1298        dialect: DialectType = None,
1299        copy: bool = True,
1300        **opts,
1301    ) -> Delete:
1302        """
1303        Set the RETURNING expression. Not supported by all dialects.
1304
1305        Example:
1306            >>> delete("tbl").returning("*", dialect="postgres").sql()
1307            'DELETE FROM tbl RETURNING *'
1308
1309        Args:
1310            expression: the SQL code strings to parse.
1311                If an `Expression` instance is passed, it will be used as-is.
1312            dialect: the dialect used to parse the input expressions.
1313            copy: if `False`, modify this expression instance in-place.
1314            opts: other options to use to parse the input expressions.
1315
1316        Returns:
1317            Delete: the modified expression.
1318        """
1319        return _apply_builder(
1320            expression=expression,
1321            instance=self,
1322            arg="returning",
1323            prefix="RETURNING",
1324            dialect=dialect,
1325            copy=copy,
1326            into=Returning,
1327            **opts,
1328        )
1329
1330
1331class Drop(Expression):
1332    arg_types = {
1333        "this": False,
1334        "kind": False,
1335        "exists": False,
1336        "temporary": False,
1337        "materialized": False,
1338        "cascade": False,
1339        "constraints": False,
1340        "purge": False,
1341    }
1342
1343
1344class Filter(Expression):
1345    arg_types = {"this": True, "expression": True}
1346
1347
1348class Check(Expression):
1349    pass
1350
1351
1352class Directory(Expression):
1353    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1354    arg_types = {"this": True, "local": False, "row_format": False}
1355
1356
1357class ForeignKey(Expression):
1358    arg_types = {
1359        "expressions": True,
1360        "reference": False,
1361        "delete": False,
1362        "update": False,
1363    }
1364
1365
1366class PrimaryKey(Expression):
1367    arg_types = {"expressions": True, "options": False}
1368
1369
1370class Unique(Expression):
1371    arg_types = {"expressions": True}
1372
1373
1374# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1375# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1376class Into(Expression):
1377    arg_types = {"this": True, "temporary": False, "unlogged": False}
1378
1379
1380class From(Expression):
1381    arg_types = {"expressions": True}
1382
1383
1384class Having(Expression):
1385    pass
1386
1387
1388class Hint(Expression):
1389    arg_types = {"expressions": True}
1390
1391
1392class JoinHint(Expression):
1393    arg_types = {"this": True, "expressions": True}
1394
1395
1396class Identifier(Expression):
1397    arg_types = {"this": True, "quoted": False}
1398
1399    @property
1400    def quoted(self):
1401        return bool(self.args.get("quoted"))
1402
1403    @property
1404    def hashable_args(self) -> t.Any:
1405        if self.quoted and any(char.isupper() for char in self.this):
1406            return (self.this, self.quoted)
1407        return self.this.lower()
1408
1409    @property
1410    def output_name(self):
1411        return self.name
1412
1413
1414class Index(Expression):
1415    arg_types = {
1416        "this": False,
1417        "table": False,
1418        "where": False,
1419        "columns": False,
1420        "unique": False,
1421        "primary": False,
1422        "amp": False,  # teradata
1423    }
1424
1425
1426class Insert(Expression):
1427    arg_types = {
1428        "with": False,
1429        "this": True,
1430        "expression": False,
1431        "conflict": False,
1432        "returning": False,
1433        "overwrite": False,
1434        "exists": False,
1435        "partition": False,
1436        "alternative": False,
1437    }
1438
1439
1440class OnConflict(Expression):
1441    arg_types = {
1442        "duplicate": False,
1443        "expressions": False,
1444        "nothing": False,
1445        "key": False,
1446        "constraint": False,
1447    }
1448
1449
1450class Returning(Expression):
1451    arg_types = {"expressions": True}
1452
1453
1454# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1455class Introducer(Expression):
1456    arg_types = {"this": True, "expression": True}
1457
1458
1459# national char, like n'utf8'
1460class National(Expression):
1461    pass
1462
1463
1464class LoadData(Expression):
1465    arg_types = {
1466        "this": True,
1467        "local": False,
1468        "overwrite": False,
1469        "inpath": True,
1470        "partition": False,
1471        "input_format": False,
1472        "serde": False,
1473    }
1474
1475
1476class Partition(Expression):
1477    arg_types = {"expressions": True}
1478
1479
1480class Fetch(Expression):
1481    arg_types = {
1482        "direction": False,
1483        "count": False,
1484        "percent": False,
1485        "with_ties": False,
1486    }
1487
1488
1489class Group(Expression):
1490    arg_types = {
1491        "expressions": False,
1492        "grouping_sets": False,
1493        "cube": False,
1494        "rollup": False,
1495    }
1496
1497
1498class Lambda(Expression):
1499    arg_types = {"this": True, "expressions": True}
1500
1501
1502class Limit(Expression):
1503    arg_types = {"this": False, "expression": True}
1504
1505
1506class Literal(Condition):
1507    arg_types = {"this": True, "is_string": True}
1508
1509    @property
1510    def hashable_args(self) -> t.Any:
1511        return (self.this, self.args.get("is_string"))
1512
1513    @classmethod
1514    def number(cls, number) -> Literal:
1515        return cls(this=str(number), is_string=False)
1516
1517    @classmethod
1518    def string(cls, string) -> Literal:
1519        return cls(this=str(string), is_string=True)
1520
1521    @property
1522    def output_name(self):
1523        return self.name
1524
1525
1526class Join(Expression):
1527    arg_types = {
1528        "this": True,
1529        "on": False,
1530        "side": False,
1531        "kind": False,
1532        "using": False,
1533        "natural": False,
1534        "hint": False,
1535    }
1536
1537    @property
1538    def kind(self):
1539        return self.text("kind").upper()
1540
1541    @property
1542    def side(self):
1543        return self.text("side").upper()
1544
1545    @property
1546    def hint(self):
1547        return self.text("hint").upper()
1548
1549    @property
1550    def alias_or_name(self):
1551        return self.this.alias_or_name
1552
1553    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1554        """
1555        Append to or set the ON expressions.
1556
1557        Example:
1558            >>> import sqlglot
1559            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1560            'JOIN x ON y = 1'
1561
1562        Args:
1563            *expressions (str | Expression): the SQL code strings to parse.
1564                If an `Expression` instance is passed, it will be used as-is.
1565                Multiple expressions are combined with an AND operator.
1566            append (bool): if `True`, AND the new expressions to any existing expression.
1567                Otherwise, this resets the expression.
1568            dialect (str): the dialect used to parse the input expressions.
1569            copy (bool): if `False`, modify this expression instance in-place.
1570            opts (kwargs): other options to use to parse the input expressions.
1571
1572        Returns:
1573            Join: the modified join expression.
1574        """
1575        join = _apply_conjunction_builder(
1576            *expressions,
1577            instance=self,
1578            arg="on",
1579            append=append,
1580            dialect=dialect,
1581            copy=copy,
1582            **opts,
1583        )
1584
1585        if join.kind == "CROSS":
1586            join.set("kind", None)
1587
1588        return join
1589
1590    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1591        """
1592        Append to or set the USING expressions.
1593
1594        Example:
1595            >>> import sqlglot
1596            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1597            'JOIN x USING (foo, bla)'
1598
1599        Args:
1600            *expressions (str | Expression): the SQL code strings to parse.
1601                If an `Expression` instance is passed, it will be used as-is.
1602            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1603                Otherwise, this resets the expression.
1604            dialect (str): the dialect used to parse the input expressions.
1605            copy (bool): if `False`, modify this expression instance in-place.
1606            opts (kwargs): other options to use to parse the input expressions.
1607
1608        Returns:
1609            Join: the modified join expression.
1610        """
1611        join = _apply_list_builder(
1612            *expressions,
1613            instance=self,
1614            arg="using",
1615            append=append,
1616            dialect=dialect,
1617            copy=copy,
1618            **opts,
1619        )
1620
1621        if join.kind == "CROSS":
1622            join.set("kind", None)
1623
1624        return join
1625
1626
1627class Lateral(UDTF):
1628    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1629
1630
1631class MatchRecognize(Expression):
1632    arg_types = {
1633        "partition_by": False,
1634        "order": False,
1635        "measures": False,
1636        "rows": False,
1637        "after": False,
1638        "pattern": False,
1639        "define": False,
1640        "alias": False,
1641    }
1642
1643
1644# Clickhouse FROM FINAL modifier
1645# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1646class Final(Expression):
1647    pass
1648
1649
1650class Offset(Expression):
1651    arg_types = {"this": False, "expression": True}
1652
1653
1654class Order(Expression):
1655    arg_types = {"this": False, "expressions": True}
1656
1657
1658# hive specific sorts
1659# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1660class Cluster(Order):
1661    pass
1662
1663
1664class Distribute(Order):
1665    pass
1666
1667
1668class Sort(Order):
1669    pass
1670
1671
1672class Ordered(Expression):
1673    arg_types = {"this": True, "desc": True, "nulls_first": True}
1674
1675
1676class Property(Expression):
1677    arg_types = {"this": True, "value": True}
1678
1679
1680class AfterJournalProperty(Property):
1681    arg_types = {"no": True, "dual": False, "local": False}
1682
1683
1684class AlgorithmProperty(Property):
1685    arg_types = {"this": True}
1686
1687
1688class AutoIncrementProperty(Property):
1689    arg_types = {"this": True}
1690
1691
1692class BlockCompressionProperty(Property):
1693    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1694
1695
1696class CharacterSetProperty(Property):
1697    arg_types = {"this": True, "default": True}
1698
1699
1700class ChecksumProperty(Property):
1701    arg_types = {"on": False, "default": False}
1702
1703
1704class CollateProperty(Property):
1705    arg_types = {"this": True}
1706
1707
1708class DataBlocksizeProperty(Property):
1709    arg_types = {"size": False, "units": False, "min": False, "default": False}
1710
1711
1712class DefinerProperty(Property):
1713    arg_types = {"this": True}
1714
1715
1716class DistKeyProperty(Property):
1717    arg_types = {"this": True}
1718
1719
1720class DistStyleProperty(Property):
1721    arg_types = {"this": True}
1722
1723
1724class EngineProperty(Property):
1725    arg_types = {"this": True}
1726
1727
1728class ExecuteAsProperty(Property):
1729    arg_types = {"this": True}
1730
1731
1732class ExternalProperty(Property):
1733    arg_types = {"this": False}
1734
1735
1736class FallbackProperty(Property):
1737    arg_types = {"no": True, "protection": False}
1738
1739
1740class FileFormatProperty(Property):
1741    arg_types = {"this": True}
1742
1743
1744class FreespaceProperty(Property):
1745    arg_types = {"this": True, "percent": False}
1746
1747
1748class InputOutputFormat(Expression):
1749    arg_types = {"input_format": False, "output_format": False}
1750
1751
1752class IsolatedLoadingProperty(Property):
1753    arg_types = {
1754        "no": True,
1755        "concurrent": True,
1756        "for_all": True,
1757        "for_insert": True,
1758        "for_none": True,
1759    }
1760
1761
1762class JournalProperty(Property):
1763    arg_types = {"no": True, "dual": False, "before": False}
1764
1765
1766class LanguageProperty(Property):
1767    arg_types = {"this": True}
1768
1769
1770class LikeProperty(Property):
1771    arg_types = {"this": True, "expressions": False}
1772
1773
1774class LocationProperty(Property):
1775    arg_types = {"this": True}
1776
1777
1778class LockingProperty(Property):
1779    arg_types = {
1780        "this": False,
1781        "kind": True,
1782        "for_or_in": True,
1783        "lock_type": True,
1784        "override": False,
1785    }
1786
1787
1788class LogProperty(Property):
1789    arg_types = {"no": True}
1790
1791
1792class MaterializedProperty(Property):
1793    arg_types = {"this": False}
1794
1795
1796class MergeBlockRatioProperty(Property):
1797    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1798
1799
1800class NoPrimaryIndexProperty(Property):
1801    arg_types = {"this": False}
1802
1803
1804class OnCommitProperty(Property):
1805    arg_type = {"this": False}
1806
1807
1808class PartitionedByProperty(Property):
1809    arg_types = {"this": True}
1810
1811
1812class ReturnsProperty(Property):
1813    arg_types = {"this": True, "is_table": False, "table": False}
1814
1815
1816class RowFormatProperty(Property):
1817    arg_types = {"this": True}
1818
1819
1820class RowFormatDelimitedProperty(Property):
1821    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1822    arg_types = {
1823        "fields": False,
1824        "escaped": False,
1825        "collection_items": False,
1826        "map_keys": False,
1827        "lines": False,
1828        "null": False,
1829        "serde": False,
1830    }
1831
1832
1833class RowFormatSerdeProperty(Property):
1834    arg_types = {"this": True}
1835
1836
1837class SchemaCommentProperty(Property):
1838    arg_types = {"this": True}
1839
1840
1841class SerdeProperties(Property):
1842    arg_types = {"expressions": True}
1843
1844
1845class SetProperty(Property):
1846    arg_types = {"multi": True}
1847
1848
1849class SortKeyProperty(Property):
1850    arg_types = {"this": True, "compound": False}
1851
1852
1853class SqlSecurityProperty(Property):
1854    arg_types = {"definer": True}
1855
1856
1857class StabilityProperty(Property):
1858    arg_types = {"this": True}
1859
1860
1861class TableFormatProperty(Property):
1862    arg_types = {"this": True}
1863
1864
1865class TemporaryProperty(Property):
1866    arg_types = {"global_": True}
1867
1868
1869class TransientProperty(Property):
1870    arg_types = {"this": False}
1871
1872
1873class VolatileProperty(Property):
1874    arg_types = {"this": False}
1875
1876
1877class WithDataProperty(Property):
1878    arg_types = {"no": True, "statistics": False}
1879
1880
1881class WithJournalTableProperty(Property):
1882    arg_types = {"this": True}
1883
1884
1885class Properties(Expression):
1886    arg_types = {"expressions": True}
1887
1888    NAME_TO_PROPERTY = {
1889        "ALGORITHM": AlgorithmProperty,
1890        "AUTO_INCREMENT": AutoIncrementProperty,
1891        "CHARACTER SET": CharacterSetProperty,
1892        "COLLATE": CollateProperty,
1893        "COMMENT": SchemaCommentProperty,
1894        "DEFINER": DefinerProperty,
1895        "DISTKEY": DistKeyProperty,
1896        "DISTSTYLE": DistStyleProperty,
1897        "ENGINE": EngineProperty,
1898        "EXECUTE AS": ExecuteAsProperty,
1899        "FORMAT": FileFormatProperty,
1900        "LANGUAGE": LanguageProperty,
1901        "LOCATION": LocationProperty,
1902        "PARTITIONED_BY": PartitionedByProperty,
1903        "RETURNS": ReturnsProperty,
1904        "ROW_FORMAT": RowFormatProperty,
1905        "SORTKEY": SortKeyProperty,
1906        "TABLE_FORMAT": TableFormatProperty,
1907    }
1908
1909    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1910
1911    # CREATE property locations
1912    # Form: schema specified
1913    #   create [POST_CREATE]
1914    #     table a [POST_NAME]
1915    #     (b int) [POST_SCHEMA]
1916    #     with ([POST_WITH])
1917    #     index (b) [POST_INDEX]
1918    #
1919    # Form: alias selection
1920    #   create [POST_CREATE]
1921    #     table a [POST_NAME]
1922    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1923    #     index (c) [POST_INDEX]
1924    class Location(AutoName):
1925        POST_CREATE = auto()
1926        POST_NAME = auto()
1927        POST_SCHEMA = auto()
1928        POST_WITH = auto()
1929        POST_ALIAS = auto()
1930        POST_EXPRESSION = auto()
1931        POST_INDEX = auto()
1932        UNSUPPORTED = auto()
1933
1934    @classmethod
1935    def from_dict(cls, properties_dict) -> Properties:
1936        expressions = []
1937        for key, value in properties_dict.items():
1938            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1939            if property_cls:
1940                expressions.append(property_cls(this=convert(value)))
1941            else:
1942                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1943
1944        return cls(expressions=expressions)
1945
1946
1947class Qualify(Expression):
1948    pass
1949
1950
1951# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1952class Return(Expression):
1953    pass
1954
1955
1956class Reference(Expression):
1957    arg_types = {"this": True, "expressions": False, "options": False}
1958
1959
1960class Tuple(Expression):
1961    arg_types = {"expressions": False}
1962
1963    def isin(
1964        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
1965    ) -> In:
1966        return In(
1967            this=_maybe_copy(self, copy),
1968            expressions=[convert(e, copy=copy) for e in expressions],
1969            query=maybe_parse(query, copy=copy, **opts) if query else None,
1970        )
1971
1972
1973class Subqueryable(Unionable):
1974    def subquery(self, alias=None, copy=True) -> Subquery:
1975        """
1976        Convert this expression to an aliased expression that can be used as a Subquery.
1977
1978        Example:
1979            >>> subquery = Select().select("x").from_("tbl").subquery()
1980            >>> Select().select("x").from_(subquery).sql()
1981            'SELECT x FROM (SELECT x FROM tbl)'
1982
1983        Args:
1984            alias (str | Identifier): an optional alias for the subquery
1985            copy (bool): if `False`, modify this expression instance in-place.
1986
1987        Returns:
1988            Alias: the subquery
1989        """
1990        instance = _maybe_copy(self, copy)
1991        return Subquery(
1992            this=instance,
1993            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1994        )
1995
1996    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1997        raise NotImplementedError
1998
1999    @property
2000    def ctes(self):
2001        with_ = self.args.get("with")
2002        if not with_:
2003            return []
2004        return with_.expressions
2005
2006    @property
2007    def selects(self):
2008        raise NotImplementedError("Subqueryable objects must implement `selects`")
2009
2010    @property
2011    def named_selects(self):
2012        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2013
2014    def with_(
2015        self,
2016        alias,
2017        as_,
2018        recursive=None,
2019        append=True,
2020        dialect=None,
2021        copy=True,
2022        **opts,
2023    ):
2024        """
2025        Append to or set the common table expressions.
2026
2027        Example:
2028            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2029            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2030
2031        Args:
2032            alias (str | Expression): the SQL code string to parse as the table name.
2033                If an `Expression` instance is passed, this is used as-is.
2034            as_ (str | Expression): the SQL code string to parse as the table expression.
2035                If an `Expression` instance is passed, it will be used as-is.
2036            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2037            append (bool): if `True`, add to any existing expressions.
2038                Otherwise, this resets the expressions.
2039            dialect (str): the dialect used to parse the input expression.
2040            copy (bool): if `False`, modify this expression instance in-place.
2041            opts (kwargs): other options to use to parse the input expressions.
2042
2043        Returns:
2044            Select: the modified expression.
2045        """
2046        alias_expression = maybe_parse(
2047            alias,
2048            dialect=dialect,
2049            into=TableAlias,
2050            **opts,
2051        )
2052        as_expression = maybe_parse(
2053            as_,
2054            dialect=dialect,
2055            **opts,
2056        )
2057        cte = CTE(
2058            this=as_expression,
2059            alias=alias_expression,
2060        )
2061        return _apply_child_list_builder(
2062            cte,
2063            instance=self,
2064            arg="with",
2065            append=append,
2066            copy=copy,
2067            into=With,
2068            properties={"recursive": recursive or False},
2069        )
2070
2071
2072QUERY_MODIFIERS = {
2073    "match": False,
2074    "laterals": False,
2075    "joins": False,
2076    "pivots": False,
2077    "where": False,
2078    "group": False,
2079    "having": False,
2080    "qualify": False,
2081    "windows": False,
2082    "distribute": False,
2083    "sort": False,
2084    "cluster": False,
2085    "order": False,
2086    "limit": False,
2087    "offset": False,
2088    "lock": False,
2089    "sample": False,
2090}
2091
2092
2093class Table(Expression):
2094    arg_types = {
2095        "this": True,
2096        "alias": False,
2097        "db": False,
2098        "catalog": False,
2099        "laterals": False,
2100        "joins": False,
2101        "pivots": False,
2102        "hints": False,
2103        "system_time": False,
2104    }
2105
2106    @property
2107    def db(self) -> str:
2108        return self.text("db")
2109
2110    @property
2111    def catalog(self) -> str:
2112        return self.text("catalog")
2113
2114
2115# See the TSQL "Querying data in a system-versioned temporal table" page
2116class SystemTime(Expression):
2117    arg_types = {
2118        "this": False,
2119        "expression": False,
2120        "kind": True,
2121    }
2122
2123
2124class Union(Subqueryable):
2125    arg_types = {
2126        "with": False,
2127        "this": True,
2128        "expression": True,
2129        "distinct": False,
2130        **QUERY_MODIFIERS,
2131    }
2132
2133    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2134        """
2135        Set the LIMIT expression.
2136
2137        Example:
2138            >>> select("1").union(select("1")).limit(1).sql()
2139            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2140
2141        Args:
2142            expression (str | int | Expression): the SQL code string to parse.
2143                This can also be an integer.
2144                If a `Limit` instance is passed, this is used as-is.
2145                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2146            dialect (str): the dialect used to parse the input expression.
2147            copy (bool): if `False`, modify this expression instance in-place.
2148            opts (kwargs): other options to use to parse the input expressions.
2149
2150        Returns:
2151            Select: The limited subqueryable.
2152        """
2153        return (
2154            select("*")
2155            .from_(self.subquery(alias="_l_0", copy=copy))
2156            .limit(expression, dialect=dialect, copy=False, **opts)
2157        )
2158
2159    def select(
2160        self,
2161        *expressions: ExpOrStr,
2162        append: bool = True,
2163        dialect: DialectType = None,
2164        copy: bool = True,
2165        **opts,
2166    ) -> Union:
2167        """Append to or set the SELECT of the union recursively.
2168
2169        Example:
2170            >>> from sqlglot import parse_one
2171            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2172            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2173
2174        Args:
2175            *expressions: the SQL code strings to parse.
2176                If an `Expression` instance is passed, it will be used as-is.
2177            append: if `True`, add to any existing expressions.
2178                Otherwise, this resets the expressions.
2179            dialect: the dialect used to parse the input expressions.
2180            copy: if `False`, modify this expression instance in-place.
2181            opts: other options to use to parse the input expressions.
2182
2183        Returns:
2184            Union: the modified expression.
2185        """
2186        this = self.copy() if copy else self
2187        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2188        this.expression.unnest().select(
2189            *expressions, append=append, dialect=dialect, copy=False, **opts
2190        )
2191        return this
2192
2193    @property
2194    def named_selects(self):
2195        return self.this.unnest().named_selects
2196
2197    @property
2198    def is_star(self) -> bool:
2199        return self.this.is_star or self.expression.is_star
2200
2201    @property
2202    def selects(self):
2203        return self.this.unnest().selects
2204
2205    @property
2206    def left(self):
2207        return self.this
2208
2209    @property
2210    def right(self):
2211        return self.expression
2212
2213
2214class Except(Union):
2215    pass
2216
2217
2218class Intersect(Union):
2219    pass
2220
2221
2222class Unnest(UDTF):
2223    arg_types = {
2224        "expressions": True,
2225        "ordinality": False,
2226        "alias": False,
2227        "offset": False,
2228    }
2229
2230
2231class Update(Expression):
2232    arg_types = {
2233        "with": False,
2234        "this": False,
2235        "expressions": True,
2236        "from": False,
2237        "where": False,
2238        "returning": False,
2239    }
2240
2241
2242class Values(UDTF):
2243    arg_types = {
2244        "expressions": True,
2245        "ordinality": False,
2246        "alias": False,
2247    }
2248
2249
2250class Var(Expression):
2251    pass
2252
2253
2254class Schema(Expression):
2255    arg_types = {"this": False, "expressions": False}
2256
2257
2258# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2259# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2260class Lock(Expression):
2261    arg_types = {"update": True}
2262
2263
2264class Select(Subqueryable):
2265    arg_types = {
2266        "with": False,
2267        "kind": False,
2268        "expressions": False,
2269        "hint": False,
2270        "distinct": False,
2271        "struct": False,  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table
2272        "value": False,
2273        "into": False,
2274        "from": False,
2275        **QUERY_MODIFIERS,
2276    }
2277
2278    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2279        """
2280        Set the FROM expression.
2281
2282        Example:
2283            >>> Select().from_("tbl").select("x").sql()
2284            'SELECT x FROM tbl'
2285
2286        Args:
2287            *expressions (str | Expression): the SQL code strings to parse.
2288                If a `From` instance is passed, this is used as-is.
2289                If another `Expression` instance is passed, it will be wrapped in a `From`.
2290            append (bool): if `True`, add to any existing expressions.
2291                Otherwise, this flattens all the `From` expression into a single expression.
2292            dialect (str): the dialect used to parse the input expression.
2293            copy (bool): if `False`, modify this expression instance in-place.
2294            opts (kwargs): other options to use to parse the input expressions.
2295
2296        Returns:
2297            Select: the modified expression.
2298        """
2299        return _apply_child_list_builder(
2300            *expressions,
2301            instance=self,
2302            arg="from",
2303            append=append,
2304            copy=copy,
2305            prefix="FROM",
2306            into=From,
2307            dialect=dialect,
2308            **opts,
2309        )
2310
2311    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2312        """
2313        Set the GROUP BY expression.
2314
2315        Example:
2316            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2317            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2318
2319        Args:
2320            *expressions (str | Expression): the SQL code strings to parse.
2321                If a `Group` instance is passed, this is used as-is.
2322                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2323                If nothing is passed in then a group by is not applied to the expression
2324            append (bool): if `True`, add to any existing expressions.
2325                Otherwise, this flattens all the `Group` expression into a single expression.
2326            dialect (str): the dialect used to parse the input expression.
2327            copy (bool): if `False`, modify this expression instance in-place.
2328            opts (kwargs): other options to use to parse the input expressions.
2329
2330        Returns:
2331            Select: the modified expression.
2332        """
2333        if not expressions:
2334            return self if not copy else self.copy()
2335        return _apply_child_list_builder(
2336            *expressions,
2337            instance=self,
2338            arg="group",
2339            append=append,
2340            copy=copy,
2341            prefix="GROUP BY",
2342            into=Group,
2343            dialect=dialect,
2344            **opts,
2345        )
2346
2347    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2348        """
2349        Set the ORDER BY expression.
2350
2351        Example:
2352            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2353            'SELECT x FROM tbl ORDER BY x DESC'
2354
2355        Args:
2356            *expressions (str | Expression): the SQL code strings to parse.
2357                If a `Group` instance is passed, this is used as-is.
2358                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2359            append (bool): if `True`, add to any existing expressions.
2360                Otherwise, this flattens all the `Order` expression into a single expression.
2361            dialect (str): the dialect used to parse the input expression.
2362            copy (bool): if `False`, modify this expression instance in-place.
2363            opts (kwargs): other options to use to parse the input expressions.
2364
2365        Returns:
2366            Select: the modified expression.
2367        """
2368        return _apply_child_list_builder(
2369            *expressions,
2370            instance=self,
2371            arg="order",
2372            append=append,
2373            copy=copy,
2374            prefix="ORDER BY",
2375            into=Order,
2376            dialect=dialect,
2377            **opts,
2378        )
2379
2380    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2381        """
2382        Set the SORT BY expression.
2383
2384        Example:
2385            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2386            'SELECT x FROM tbl SORT BY x DESC'
2387
2388        Args:
2389            *expressions (str | Expression): the SQL code strings to parse.
2390                If a `Group` instance is passed, this is used as-is.
2391                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2392            append (bool): if `True`, add to any existing expressions.
2393                Otherwise, this flattens all the `Order` expression into a single expression.
2394            dialect (str): the dialect used to parse the input expression.
2395            copy (bool): if `False`, modify this expression instance in-place.
2396            opts (kwargs): other options to use to parse the input expressions.
2397
2398        Returns:
2399            Select: the modified expression.
2400        """
2401        return _apply_child_list_builder(
2402            *expressions,
2403            instance=self,
2404            arg="sort",
2405            append=append,
2406            copy=copy,
2407            prefix="SORT BY",
2408            into=Sort,
2409            dialect=dialect,
2410            **opts,
2411        )
2412
2413    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2414        """
2415        Set the CLUSTER BY expression.
2416
2417        Example:
2418            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2419            'SELECT x FROM tbl CLUSTER BY x DESC'
2420
2421        Args:
2422            *expressions (str | Expression): the SQL code strings to parse.
2423                If a `Group` instance is passed, this is used as-is.
2424                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2425            append (bool): if `True`, add to any existing expressions.
2426                Otherwise, this flattens all the `Order` expression into a single expression.
2427            dialect (str): the dialect used to parse the input expression.
2428            copy (bool): if `False`, modify this expression instance in-place.
2429            opts (kwargs): other options to use to parse the input expressions.
2430
2431        Returns:
2432            Select: the modified expression.
2433        """
2434        return _apply_child_list_builder(
2435            *expressions,
2436            instance=self,
2437            arg="cluster",
2438            append=append,
2439            copy=copy,
2440            prefix="CLUSTER BY",
2441            into=Cluster,
2442            dialect=dialect,
2443            **opts,
2444        )
2445
2446    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2447        """
2448        Set the LIMIT expression.
2449
2450        Example:
2451            >>> Select().from_("tbl").select("x").limit(10).sql()
2452            'SELECT x FROM tbl LIMIT 10'
2453
2454        Args:
2455            expression (str | int | Expression): the SQL code string to parse.
2456                This can also be an integer.
2457                If a `Limit` instance is passed, this is used as-is.
2458                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2459            dialect (str): the dialect used to parse the input expression.
2460            copy (bool): if `False`, modify this expression instance in-place.
2461            opts (kwargs): other options to use to parse the input expressions.
2462
2463        Returns:
2464            Select: the modified expression.
2465        """
2466        return _apply_builder(
2467            expression=expression,
2468            instance=self,
2469            arg="limit",
2470            into=Limit,
2471            prefix="LIMIT",
2472            dialect=dialect,
2473            copy=copy,
2474            **opts,
2475        )
2476
2477    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2478        """
2479        Set the OFFSET expression.
2480
2481        Example:
2482            >>> Select().from_("tbl").select("x").offset(10).sql()
2483            'SELECT x FROM tbl OFFSET 10'
2484
2485        Args:
2486            expression (str | int | Expression): the SQL code string to parse.
2487                This can also be an integer.
2488                If a `Offset` instance is passed, this is used as-is.
2489                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2490            dialect (str): the dialect used to parse the input expression.
2491            copy (bool): if `False`, modify this expression instance in-place.
2492            opts (kwargs): other options to use to parse the input expressions.
2493
2494        Returns:
2495            Select: the modified expression.
2496        """
2497        return _apply_builder(
2498            expression=expression,
2499            instance=self,
2500            arg="offset",
2501            into=Offset,
2502            prefix="OFFSET",
2503            dialect=dialect,
2504            copy=copy,
2505            **opts,
2506        )
2507
2508    def select(
2509        self,
2510        *expressions: ExpOrStr,
2511        append: bool = True,
2512        dialect: DialectType = None,
2513        copy: bool = True,
2514        **opts,
2515    ) -> Select:
2516        """
2517        Append to or set the SELECT expressions.
2518
2519        Example:
2520            >>> Select().select("x", "y").sql()
2521            'SELECT x, y'
2522
2523        Args:
2524            *expressions: the SQL code strings to parse.
2525                If an `Expression` instance is passed, it will be used as-is.
2526            append: if `True`, add to any existing expressions.
2527                Otherwise, this resets the expressions.
2528            dialect: the dialect used to parse the input expressions.
2529            copy: if `False`, modify this expression instance in-place.
2530            opts: other options to use to parse the input expressions.
2531
2532        Returns:
2533            Select: the modified expression.
2534        """
2535        return _apply_list_builder(
2536            *expressions,
2537            instance=self,
2538            arg="expressions",
2539            append=append,
2540            dialect=dialect,
2541            copy=copy,
2542            **opts,
2543        )
2544
2545    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2546        """
2547        Append to or set the LATERAL expressions.
2548
2549        Example:
2550            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2551            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2552
2553        Args:
2554            *expressions (str | Expression): the SQL code strings to parse.
2555                If an `Expression` instance is passed, it will be used as-is.
2556            append (bool): if `True`, add to any existing expressions.
2557                Otherwise, this resets the expressions.
2558            dialect (str): the dialect used to parse the input expressions.
2559            copy (bool): if `False`, modify this expression instance in-place.
2560            opts (kwargs): other options to use to parse the input expressions.
2561
2562        Returns:
2563            Select: the modified expression.
2564        """
2565        return _apply_list_builder(
2566            *expressions,
2567            instance=self,
2568            arg="laterals",
2569            append=append,
2570            into=Lateral,
2571            prefix="LATERAL VIEW",
2572            dialect=dialect,
2573            copy=copy,
2574            **opts,
2575        )
2576
2577    def join(
2578        self,
2579        expression,
2580        on=None,
2581        using=None,
2582        append=True,
2583        join_type=None,
2584        join_alias=None,
2585        dialect=None,
2586        copy=True,
2587        **opts,
2588    ) -> Select:
2589        """
2590        Append to or set the JOIN expressions.
2591
2592        Example:
2593            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2594            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2595
2596            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2597            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2598
2599            Use `join_type` to change the type of join:
2600
2601            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2602            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2603
2604        Args:
2605            expression (str | Expression): the SQL code string to parse.
2606                If an `Expression` instance is passed, it will be used as-is.
2607            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2608                If an `Expression` instance is passed, it will be used as-is.
2609            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2610                If an `Expression` instance is passed, it will be used as-is.
2611            append (bool): if `True`, add to any existing expressions.
2612                Otherwise, this resets the expressions.
2613            join_type (str): If set, alter the parsed join type
2614            dialect (str): the dialect used to parse the input expressions.
2615            copy (bool): if `False`, modify this expression instance in-place.
2616            opts (kwargs): other options to use to parse the input expressions.
2617
2618        Returns:
2619            Select: the modified expression.
2620        """
2621        parse_args = {"dialect": dialect, **opts}
2622
2623        try:
2624            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2625        except ParseError:
2626            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2627
2628        join = expression if isinstance(expression, Join) else Join(this=expression)
2629
2630        if isinstance(join.this, Select):
2631            join.this.replace(join.this.subquery())
2632
2633        if join_type:
2634            natural: t.Optional[Token]
2635            side: t.Optional[Token]
2636            kind: t.Optional[Token]
2637
2638            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2639
2640            if natural:
2641                join.set("natural", True)
2642            if side:
2643                join.set("side", side.text)
2644            if kind:
2645                join.set("kind", kind.text)
2646
2647        if on:
2648            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2649            join.set("on", on)
2650
2651        if using:
2652            join = _apply_list_builder(
2653                *ensure_collection(using),
2654                instance=join,
2655                arg="using",
2656                append=append,
2657                copy=copy,
2658                **opts,
2659            )
2660
2661        if join_alias:
2662            join.set("this", alias_(join.this, join_alias, table=True))
2663        return _apply_list_builder(
2664            join,
2665            instance=self,
2666            arg="joins",
2667            append=append,
2668            copy=copy,
2669            **opts,
2670        )
2671
2672    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2673        """
2674        Append to or set the WHERE expressions.
2675
2676        Example:
2677            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2678            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2679
2680        Args:
2681            *expressions (str | Expression): the SQL code strings to parse.
2682                If an `Expression` instance is passed, it will be used as-is.
2683                Multiple expressions are combined with an AND operator.
2684            append (bool): if `True`, AND the new expressions to any existing expression.
2685                Otherwise, this resets the expression.
2686            dialect (str): the dialect used to parse the input expressions.
2687            copy (bool): if `False`, modify this expression instance in-place.
2688            opts (kwargs): other options to use to parse the input expressions.
2689
2690        Returns:
2691            Select: the modified expression.
2692        """
2693        return _apply_conjunction_builder(
2694            *expressions,
2695            instance=self,
2696            arg="where",
2697            append=append,
2698            into=Where,
2699            dialect=dialect,
2700            copy=copy,
2701            **opts,
2702        )
2703
2704    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2705        """
2706        Append to or set the HAVING expressions.
2707
2708        Example:
2709            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2710            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2711
2712        Args:
2713            *expressions (str | Expression): the SQL code strings to parse.
2714                If an `Expression` instance is passed, it will be used as-is.
2715                Multiple expressions are combined with an AND operator.
2716            append (bool): if `True`, AND the new expressions to any existing expression.
2717                Otherwise, this resets the expression.
2718            dialect (str): the dialect used to parse the input expressions.
2719            copy (bool): if `False`, modify this expression instance in-place.
2720            opts (kwargs): other options to use to parse the input expressions.
2721
2722        Returns:
2723            Select: the modified expression.
2724        """
2725        return _apply_conjunction_builder(
2726            *expressions,
2727            instance=self,
2728            arg="having",
2729            append=append,
2730            into=Having,
2731            dialect=dialect,
2732            copy=copy,
2733            **opts,
2734        )
2735
2736    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2737        return _apply_list_builder(
2738            *expressions,
2739            instance=self,
2740            arg="windows",
2741            append=append,
2742            into=Window,
2743            dialect=dialect,
2744            copy=copy,
2745            **opts,
2746        )
2747
2748    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2749        return _apply_conjunction_builder(
2750            *expressions,
2751            instance=self,
2752            arg="qualify",
2753            append=append,
2754            into=Qualify,
2755            dialect=dialect,
2756            copy=copy,
2757            **opts,
2758        )
2759
2760    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2761        """
2762        Set the OFFSET expression.
2763
2764        Example:
2765            >>> Select().from_("tbl").select("x").distinct().sql()
2766            'SELECT DISTINCT x FROM tbl'
2767
2768        Args:
2769            ons: the expressions to distinct on
2770            distinct: whether the Select should be distinct
2771            copy: if `False`, modify this expression instance in-place.
2772
2773        Returns:
2774            Select: the modified expression.
2775        """
2776        instance = _maybe_copy(self, copy)
2777        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2778        instance.set("distinct", Distinct(on=on) if distinct else None)
2779        return instance
2780
2781    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2782        """
2783        Convert this expression to a CREATE TABLE AS statement.
2784
2785        Example:
2786            >>> Select().select("*").from_("tbl").ctas("x").sql()
2787            'CREATE TABLE x AS SELECT * FROM tbl'
2788
2789        Args:
2790            table (str | Expression): the SQL code string to parse as the table name.
2791                If another `Expression` instance is passed, it will be used as-is.
2792            properties (dict): an optional mapping of table properties
2793            dialect (str): the dialect used to parse the input table.
2794            copy (bool): if `False`, modify this expression instance in-place.
2795            opts (kwargs): other options to use to parse the input table.
2796
2797        Returns:
2798            Create: the CREATE TABLE AS expression
2799        """
2800        instance = _maybe_copy(self, copy)
2801        table_expression = maybe_parse(
2802            table,
2803            into=Table,
2804            dialect=dialect,
2805            **opts,
2806        )
2807        properties_expression = None
2808        if properties:
2809            properties_expression = Properties.from_dict(properties)
2810
2811        return Create(
2812            this=table_expression,
2813            kind="table",
2814            expression=instance,
2815            properties=properties_expression,
2816        )
2817
2818    def lock(self, update: bool = True, copy: bool = True) -> Select:
2819        """
2820        Set the locking read mode for this expression.
2821
2822        Examples:
2823            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2824            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2825
2826            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2827            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2828
2829        Args:
2830            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2831            copy: if `False`, modify this expression instance in-place.
2832
2833        Returns:
2834            The modified expression.
2835        """
2836
2837        inst = _maybe_copy(self, copy)
2838        inst.set("lock", Lock(update=update))
2839
2840        return inst
2841
2842    @property
2843    def named_selects(self) -> t.List[str]:
2844        return [e.output_name for e in self.expressions if e.alias_or_name]
2845
2846    @property
2847    def is_star(self) -> bool:
2848        return any(expression.is_star for expression in self.expressions)
2849
2850    @property
2851    def selects(self) -> t.List[Expression]:
2852        return self.expressions
2853
2854
2855class Subquery(DerivedTable, Unionable):
2856    arg_types = {
2857        "this": True,
2858        "alias": False,
2859        "with": False,
2860        **QUERY_MODIFIERS,
2861    }
2862
2863    def unnest(self):
2864        """
2865        Returns the first non subquery.
2866        """
2867        expression = self
2868        while isinstance(expression, Subquery):
2869            expression = expression.this
2870        return expression
2871
2872    @property
2873    def is_star(self) -> bool:
2874        return self.this.is_star
2875
2876    @property
2877    def output_name(self):
2878        return self.alias
2879
2880
2881class TableSample(Expression):
2882    arg_types = {
2883        "this": False,
2884        "method": False,
2885        "bucket_numerator": False,
2886        "bucket_denominator": False,
2887        "bucket_field": False,
2888        "percent": False,
2889        "rows": False,
2890        "size": False,
2891        "seed": False,
2892        "kind": False,
2893    }
2894
2895
2896class Tag(Expression):
2897    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2898
2899    arg_types = {
2900        "this": False,
2901        "prefix": False,
2902        "postfix": False,
2903    }
2904
2905
2906class Pivot(Expression):
2907    arg_types = {
2908        "this": False,
2909        "alias": False,
2910        "expressions": True,
2911        "field": True,
2912        "unpivot": True,
2913        "columns": False,
2914    }
2915
2916
2917class Window(Expression):
2918    arg_types = {
2919        "this": True,
2920        "partition_by": False,
2921        "order": False,
2922        "spec": False,
2923        "alias": False,
2924        "over": False,
2925        "first": False,
2926    }
2927
2928
2929class WindowSpec(Expression):
2930    arg_types = {
2931        "kind": False,
2932        "start": False,
2933        "start_side": False,
2934        "end": False,
2935        "end_side": False,
2936    }
2937
2938
2939class Where(Expression):
2940    pass
2941
2942
2943class Star(Expression):
2944    arg_types = {"except": False, "replace": False}
2945
2946    @property
2947    def name(self) -> str:
2948        return "*"
2949
2950    @property
2951    def output_name(self):
2952        return self.name
2953
2954
2955class Parameter(Expression):
2956    arg_types = {"this": True, "wrapped": False}
2957
2958
2959class SessionParameter(Expression):
2960    arg_types = {"this": True, "kind": False}
2961
2962
2963class Placeholder(Expression):
2964    arg_types = {"this": False}
2965
2966
2967class Null(Condition):
2968    arg_types: t.Dict[str, t.Any] = {}
2969
2970    @property
2971    def name(self) -> str:
2972        return "NULL"
2973
2974
2975class Boolean(Condition):
2976    pass
2977
2978
2979class DataType(Expression):
2980    arg_types = {
2981        "this": True,
2982        "expressions": False,
2983        "nested": False,
2984        "values": False,
2985        "prefix": False,
2986    }
2987
2988    class Type(AutoName):
2989        CHAR = auto()
2990        NCHAR = auto()
2991        VARCHAR = auto()
2992        NVARCHAR = auto()
2993        TEXT = auto()
2994        MEDIUMTEXT = auto()
2995        LONGTEXT = auto()
2996        MEDIUMBLOB = auto()
2997        LONGBLOB = auto()
2998        BINARY = auto()
2999        VARBINARY = auto()
3000        INT = auto()
3001        UINT = auto()
3002        TINYINT = auto()
3003        UTINYINT = auto()
3004        SMALLINT = auto()
3005        USMALLINT = auto()
3006        BIGINT = auto()
3007        UBIGINT = auto()
3008        INT128 = auto()
3009        UINT128 = auto()
3010        INT256 = auto()
3011        UINT256 = auto()
3012        FLOAT = auto()
3013        DOUBLE = auto()
3014        DECIMAL = auto()
3015        BIGDECIMAL = auto()
3016        BIT = auto()
3017        BOOLEAN = auto()
3018        JSON = auto()
3019        JSONB = auto()
3020        INTERVAL = auto()
3021        TIME = auto()
3022        TIMESTAMP = auto()
3023        TIMESTAMPTZ = auto()
3024        TIMESTAMPLTZ = auto()
3025        DATE = auto()
3026        DATETIME = auto()
3027        ARRAY = auto()
3028        MAP = auto()
3029        UUID = auto()
3030        GEOGRAPHY = auto()
3031        GEOMETRY = auto()
3032        STRUCT = auto()
3033        NULLABLE = auto()
3034        HLLSKETCH = auto()
3035        HSTORE = auto()
3036        SUPER = auto()
3037        SERIAL = auto()
3038        SMALLSERIAL = auto()
3039        BIGSERIAL = auto()
3040        XML = auto()
3041        UNIQUEIDENTIFIER = auto()
3042        MONEY = auto()
3043        SMALLMONEY = auto()
3044        ROWVERSION = auto()
3045        IMAGE = auto()
3046        VARIANT = auto()
3047        OBJECT = auto()
3048        INET = auto()
3049        NULL = auto()
3050        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3051
3052    TEXT_TYPES = {
3053        Type.CHAR,
3054        Type.NCHAR,
3055        Type.VARCHAR,
3056        Type.NVARCHAR,
3057        Type.TEXT,
3058    }
3059
3060    INTEGER_TYPES = {
3061        Type.INT,
3062        Type.TINYINT,
3063        Type.SMALLINT,
3064        Type.BIGINT,
3065        Type.INT128,
3066        Type.INT256,
3067    }
3068
3069    FLOAT_TYPES = {
3070        Type.FLOAT,
3071        Type.DOUBLE,
3072    }
3073
3074    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3075
3076    TEMPORAL_TYPES = {
3077        Type.TIMESTAMP,
3078        Type.TIMESTAMPTZ,
3079        Type.TIMESTAMPLTZ,
3080        Type.DATE,
3081        Type.DATETIME,
3082    }
3083
3084    @classmethod
3085    def build(
3086        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3087    ) -> DataType:
3088        from sqlglot import parse_one
3089
3090        if isinstance(dtype, str):
3091            if dtype.upper() in cls.Type.__members__:
3092                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3093            else:
3094                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3095            if data_type_exp is None:
3096                raise ValueError(f"Unparsable data type value: {dtype}")
3097        elif isinstance(dtype, DataType.Type):
3098            data_type_exp = DataType(this=dtype)
3099        elif isinstance(dtype, DataType):
3100            return dtype
3101        else:
3102            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3103        return DataType(**{**data_type_exp.args, **kwargs})
3104
3105    def is_type(self, dtype: DataType.Type) -> bool:
3106        return self.this == dtype
3107
3108
3109# https://www.postgresql.org/docs/15/datatype-pseudo.html
3110class PseudoType(Expression):
3111    pass
3112
3113
3114# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3115class SubqueryPredicate(Predicate):
3116    pass
3117
3118
3119class All(SubqueryPredicate):
3120    pass
3121
3122
3123class Any(SubqueryPredicate):
3124    pass
3125
3126
3127class Exists(SubqueryPredicate):
3128    pass
3129
3130
3131# Commands to interact with the databases or engines. For most of the command
3132# expressions we parse whatever comes after the command's name as a string.
3133class Command(Expression):
3134    arg_types = {"this": True, "expression": False}
3135
3136
3137class Transaction(Expression):
3138    arg_types = {"this": False, "modes": False}
3139
3140
3141class Commit(Expression):
3142    arg_types = {"chain": False}
3143
3144
3145class Rollback(Expression):
3146    arg_types = {"savepoint": False}
3147
3148
3149class AlterTable(Expression):
3150    arg_types = {"this": True, "actions": True, "exists": False}
3151
3152
3153class AddConstraint(Expression):
3154    arg_types = {"this": False, "expression": False, "enforced": False}
3155
3156
3157class DropPartition(Expression):
3158    arg_types = {"expressions": True, "exists": False}
3159
3160
3161# Binary expressions like (ADD a b)
3162class Binary(Condition):
3163    arg_types = {"this": True, "expression": True}
3164
3165    @property
3166    def left(self):
3167        return self.this
3168
3169    @property
3170    def right(self):
3171        return self.expression
3172
3173
3174class Add(Binary):
3175    pass
3176
3177
3178class Connector(Binary):
3179    pass
3180
3181
3182class And(Connector):
3183    pass
3184
3185
3186class Or(Connector):
3187    pass
3188
3189
3190class BitwiseAnd(Binary):
3191    pass
3192
3193
3194class BitwiseLeftShift(Binary):
3195    pass
3196
3197
3198class BitwiseOr(Binary):
3199    pass
3200
3201
3202class BitwiseRightShift(Binary):
3203    pass
3204
3205
3206class BitwiseXor(Binary):
3207    pass
3208
3209
3210class Div(Binary):
3211    pass
3212
3213
3214class Overlaps(Binary):
3215    pass
3216
3217
3218class Dot(Binary):
3219    @property
3220    def name(self) -> str:
3221        return self.expression.name
3222
3223    @classmethod
3224    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3225        """Build a Dot object with a sequence of expressions."""
3226        if len(expressions) < 2:
3227            raise ValueError(f"Dot requires >= 2 expressions.")
3228
3229        a, b, *expressions = expressions
3230        dot = Dot(this=a, expression=b)
3231
3232        for expression in expressions:
3233            dot = Dot(this=dot, expression=expression)
3234
3235        return dot
3236
3237
3238class DPipe(Binary):
3239    pass
3240
3241
3242class EQ(Binary, Predicate):
3243    pass
3244
3245
3246class NullSafeEQ(Binary, Predicate):
3247    pass
3248
3249
3250class NullSafeNEQ(Binary, Predicate):
3251    pass
3252
3253
3254class Distance(Binary):
3255    pass
3256
3257
3258class Escape(Binary):
3259    pass
3260
3261
3262class Glob(Binary, Predicate):
3263    pass
3264
3265
3266class GT(Binary, Predicate):
3267    pass
3268
3269
3270class GTE(Binary, Predicate):
3271    pass
3272
3273
3274class ILike(Binary, Predicate):
3275    pass
3276
3277
3278class ILikeAny(Binary, Predicate):
3279    pass
3280
3281
3282class IntDiv(Binary):
3283    pass
3284
3285
3286class Is(Binary, Predicate):
3287    pass
3288
3289
3290class Kwarg(Binary):
3291    """Kwarg in special functions like func(kwarg => y)."""
3292
3293
3294class Like(Binary, Predicate):
3295    pass
3296
3297
3298class LikeAny(Binary, Predicate):
3299    pass
3300
3301
3302class LT(Binary, Predicate):
3303    pass
3304
3305
3306class LTE(Binary, Predicate):
3307    pass
3308
3309
3310class Mod(Binary):
3311    pass
3312
3313
3314class Mul(Binary):
3315    pass
3316
3317
3318class NEQ(Binary, Predicate):
3319    pass
3320
3321
3322class SimilarTo(Binary, Predicate):
3323    pass
3324
3325
3326class Slice(Binary):
3327    arg_types = {"this": False, "expression": False}
3328
3329
3330class Sub(Binary):
3331    pass
3332
3333
3334class ArrayOverlaps(Binary):
3335    pass
3336
3337
3338# Unary Expressions
3339# (NOT a)
3340class Unary(Condition):
3341    pass
3342
3343
3344class BitwiseNot(Unary):
3345    pass
3346
3347
3348class Not(Unary):
3349    pass
3350
3351
3352class Paren(Unary):
3353    arg_types = {"this": True, "with": False}
3354
3355
3356class Neg(Unary):
3357    pass
3358
3359
3360class Alias(Expression):
3361    arg_types = {"this": True, "alias": False}
3362
3363    @property
3364    def output_name(self):
3365        return self.alias
3366
3367
3368class Aliases(Expression):
3369    arg_types = {"this": True, "expressions": True}
3370
3371    @property
3372    def aliases(self):
3373        return self.expressions
3374
3375
3376class AtTimeZone(Expression):
3377    arg_types = {"this": True, "zone": True}
3378
3379
3380class Between(Predicate):
3381    arg_types = {"this": True, "low": True, "high": True}
3382
3383
3384class Bracket(Condition):
3385    arg_types = {"this": True, "expressions": True}
3386
3387
3388class Distinct(Expression):
3389    arg_types = {"expressions": False, "on": False}
3390
3391
3392class In(Predicate):
3393    arg_types = {
3394        "this": True,
3395        "expressions": False,
3396        "query": False,
3397        "unnest": False,
3398        "field": False,
3399        "is_global": False,
3400    }
3401
3402
3403class TimeUnit(Expression):
3404    """Automatically converts unit arg into a var."""
3405
3406    arg_types = {"unit": False}
3407
3408    def __init__(self, **args):
3409        unit = args.get("unit")
3410        if isinstance(unit, (Column, Literal)):
3411            args["unit"] = Var(this=unit.name)
3412        elif isinstance(unit, Week):
3413            unit.set("this", Var(this=unit.this.name))
3414        super().__init__(**args)
3415
3416
3417class Interval(TimeUnit):
3418    arg_types = {"this": False, "unit": False}
3419
3420
3421class IgnoreNulls(Expression):
3422    pass
3423
3424
3425class RespectNulls(Expression):
3426    pass
3427
3428
3429# Functions
3430class Func(Condition):
3431    """
3432    The base class for all function expressions.
3433
3434    Attributes:
3435        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3436            treated as a variable length argument and the argument's value will be stored as a list.
3437        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3438            for this function expression. These values are used to map this node to a name during parsing
3439            as well as to provide the function's name during SQL string generation. By default the SQL
3440            name is set to the expression's class name transformed to snake case.
3441    """
3442
3443    is_var_len_args = False
3444
3445    @classmethod
3446    def from_arg_list(cls, args):
3447        if cls.is_var_len_args:
3448            all_arg_keys = list(cls.arg_types)
3449            # If this function supports variable length argument treat the last argument as such.
3450            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3451            num_non_var = len(non_var_len_arg_keys)
3452
3453            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3454            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3455        else:
3456            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3457
3458        return cls(**args_dict)
3459
3460    @classmethod
3461    def sql_names(cls):
3462        if cls is Func:
3463            raise NotImplementedError(
3464                "SQL name is only supported by concrete function implementations"
3465            )
3466        if "_sql_names" not in cls.__dict__:
3467            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3468        return cls._sql_names
3469
3470    @classmethod
3471    def sql_name(cls):
3472        return cls.sql_names()[0]
3473
3474    @classmethod
3475    def default_parser_mappings(cls):
3476        return {name: cls.from_arg_list for name in cls.sql_names()}
3477
3478
3479class AggFunc(Func):
3480    pass
3481
3482
3483class Abs(Func):
3484    pass
3485
3486
3487class Anonymous(Func):
3488    arg_types = {"this": True, "expressions": False}
3489    is_var_len_args = True
3490
3491
3492# https://docs.snowflake.com/en/sql-reference/functions/hll
3493# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3494class Hll(AggFunc):
3495    arg_types = {"this": True, "expressions": False}
3496    is_var_len_args = True
3497
3498
3499class ApproxDistinct(AggFunc):
3500    arg_types = {"this": True, "accuracy": False}
3501
3502
3503class Array(Func):
3504    arg_types = {"expressions": False}
3505    is_var_len_args = True
3506
3507
3508# https://docs.snowflake.com/en/sql-reference/functions/to_char
3509class ToChar(Func):
3510    arg_types = {"this": True, "format": False}
3511
3512
3513class GenerateSeries(Func):
3514    arg_types = {"start": True, "end": True, "step": False}
3515
3516
3517class ArrayAgg(AggFunc):
3518    pass
3519
3520
3521class ArrayAll(Func):
3522    arg_types = {"this": True, "expression": True}
3523
3524
3525class ArrayAny(Func):
3526    arg_types = {"this": True, "expression": True}
3527
3528
3529class ArrayConcat(Func):
3530    arg_types = {"this": True, "expressions": False}
3531    is_var_len_args = True
3532
3533
3534class ArrayContains(Binary, Func):
3535    pass
3536
3537
3538class ArrayContained(Binary):
3539    pass
3540
3541
3542class ArrayFilter(Func):
3543    arg_types = {"this": True, "expression": True}
3544    _sql_names = ["FILTER", "ARRAY_FILTER"]
3545
3546
3547class ArrayJoin(Func):
3548    arg_types = {"this": True, "expression": True, "null": False}
3549
3550
3551class ArraySize(Func):
3552    arg_types = {"this": True, "expression": False}
3553
3554
3555class ArraySort(Func):
3556    arg_types = {"this": True, "expression": False}
3557
3558
3559class ArraySum(Func):
3560    pass
3561
3562
3563class ArrayUnionAgg(AggFunc):
3564    pass
3565
3566
3567class Avg(AggFunc):
3568    pass
3569
3570
3571class AnyValue(AggFunc):
3572    pass
3573
3574
3575class Case(Func):
3576    arg_types = {"this": False, "ifs": True, "default": False}
3577
3578    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3579        instance = _maybe_copy(self, copy)
3580        instance.append(
3581            "ifs",
3582            If(
3583                this=maybe_parse(condition, copy=copy, **opts),
3584                true=maybe_parse(then, copy=copy, **opts),
3585            ),
3586        )
3587        return instance
3588
3589    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3590        instance = _maybe_copy(self, copy)
3591        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3592        return instance
3593
3594
3595class Cast(Func):
3596    arg_types = {"this": True, "to": True}
3597
3598    @property
3599    def name(self) -> str:
3600        return self.this.name
3601
3602    @property
3603    def to(self):
3604        return self.args["to"]
3605
3606    @property
3607    def output_name(self):
3608        return self.name
3609
3610    def is_type(self, dtype: DataType.Type) -> bool:
3611        return self.to.is_type(dtype)
3612
3613
3614class Collate(Binary):
3615    pass
3616
3617
3618class TryCast(Cast):
3619    pass
3620
3621
3622class Ceil(Func):
3623    arg_types = {"this": True, "decimals": False}
3624    _sql_names = ["CEIL", "CEILING"]
3625
3626
3627class Coalesce(Func):
3628    arg_types = {"this": True, "expressions": False}
3629    is_var_len_args = True
3630
3631
3632class Concat(Func):
3633    arg_types = {"expressions": True}
3634    is_var_len_args = True
3635
3636
3637class ConcatWs(Concat):
3638    _sql_names = ["CONCAT_WS"]
3639
3640
3641class Count(AggFunc):
3642    arg_types = {"this": False}
3643
3644
3645class CountIf(AggFunc):
3646    pass
3647
3648
3649class CurrentDate(Func):
3650    arg_types = {"this": False}
3651
3652
3653class CurrentDatetime(Func):
3654    arg_types = {"this": False}
3655
3656
3657class CurrentTime(Func):
3658    arg_types = {"this": False}
3659
3660
3661class CurrentTimestamp(Func):
3662    arg_types = {"this": False}
3663
3664
3665class CurrentUser(Func):
3666    arg_types = {"this": False}
3667
3668
3669class DateAdd(Func, TimeUnit):
3670    arg_types = {"this": True, "expression": True, "unit": False}
3671
3672
3673class DateSub(Func, TimeUnit):
3674    arg_types = {"this": True, "expression": True, "unit": False}
3675
3676
3677class DateDiff(Func, TimeUnit):
3678    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3679    arg_types = {"this": True, "expression": True, "unit": False}
3680
3681
3682class DateTrunc(Func):
3683    arg_types = {"unit": True, "this": True, "zone": False}
3684
3685
3686class DatetimeAdd(Func, TimeUnit):
3687    arg_types = {"this": True, "expression": True, "unit": False}
3688
3689
3690class DatetimeSub(Func, TimeUnit):
3691    arg_types = {"this": True, "expression": True, "unit": False}
3692
3693
3694class DatetimeDiff(Func, TimeUnit):
3695    arg_types = {"this": True, "expression": True, "unit": False}
3696
3697
3698class DatetimeTrunc(Func, TimeUnit):
3699    arg_types = {"this": True, "unit": True, "zone": False}
3700
3701
3702class DayOfWeek(Func):
3703    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3704
3705
3706class DayOfMonth(Func):
3707    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3708
3709
3710class DayOfYear(Func):
3711    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3712
3713
3714class WeekOfYear(Func):
3715    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3716
3717
3718class LastDateOfMonth(Func):
3719    pass
3720
3721
3722class Extract(Func):
3723    arg_types = {"this": True, "expression": True}
3724
3725
3726class TimestampAdd(Func, TimeUnit):
3727    arg_types = {"this": True, "expression": True, "unit": False}
3728
3729
3730class TimestampSub(Func, TimeUnit):
3731    arg_types = {"this": True, "expression": True, "unit": False}
3732
3733
3734class TimestampDiff(Func, TimeUnit):
3735    arg_types = {"this": True, "expression": True, "unit": False}
3736
3737
3738class TimestampTrunc(Func, TimeUnit):
3739    arg_types = {"this": True, "unit": True, "zone": False}
3740
3741
3742class TimeAdd(Func, TimeUnit):
3743    arg_types = {"this": True, "expression": True, "unit": False}
3744
3745
3746class TimeSub(Func, TimeUnit):
3747    arg_types = {"this": True, "expression": True, "unit": False}
3748
3749
3750class TimeDiff(Func, TimeUnit):
3751    arg_types = {"this": True, "expression": True, "unit": False}
3752
3753
3754class TimeTrunc(Func, TimeUnit):
3755    arg_types = {"this": True, "unit": True, "zone": False}
3756
3757
3758class DateFromParts(Func):
3759    _sql_names = ["DATEFROMPARTS"]
3760    arg_types = {"year": True, "month": True, "day": True}
3761
3762
3763class DateStrToDate(Func):
3764    pass
3765
3766
3767class DateToDateStr(Func):
3768    pass
3769
3770
3771class DateToDi(Func):
3772    pass
3773
3774
3775class Day(Func):
3776    pass
3777
3778
3779class Decode(Func):
3780    arg_types = {"this": True, "charset": True, "replace": False}
3781
3782
3783class DiToDate(Func):
3784    pass
3785
3786
3787class Encode(Func):
3788    arg_types = {"this": True, "charset": True}
3789
3790
3791class Exp(Func):
3792    pass
3793
3794
3795class Explode(Func):
3796    pass
3797
3798
3799class ExponentialTimeDecayedAvg(AggFunc):
3800    arg_types = {"this": True, "time": False, "decay": False}
3801
3802
3803class Floor(Func):
3804    arg_types = {"this": True, "decimals": False}
3805
3806
3807class FromBase64(Func):
3808    pass
3809
3810
3811class ToBase64(Func):
3812    pass
3813
3814
3815class Greatest(Func):
3816    arg_types = {"this": True, "expressions": False}
3817    is_var_len_args = True
3818
3819
3820class GroupConcat(Func):
3821    arg_types = {"this": True, "separator": False}
3822
3823
3824class GroupUniqArray(AggFunc):
3825    arg_types = {"this": True, "size": False}
3826
3827
3828class Hex(Func):
3829    pass
3830
3831
3832class Histogram(AggFunc):
3833    arg_types = {"this": True, "bins": False}
3834
3835
3836class If(Func):
3837    arg_types = {"this": True, "true": True, "false": False}
3838
3839
3840class IfNull(Func):
3841    arg_types = {"this": True, "expression": False}
3842    _sql_names = ["IFNULL", "NVL"]
3843
3844
3845class Initcap(Func):
3846    pass
3847
3848
3849class JSONKeyValue(Expression):
3850    arg_types = {"this": True, "expression": True}
3851
3852
3853class JSONObject(Func):
3854    arg_types = {
3855        "expressions": False,
3856        "null_handling": False,
3857        "unique_keys": False,
3858        "return_type": False,
3859        "format_json": False,
3860        "encoding": False,
3861    }
3862
3863
3864class JSONBContains(Binary):
3865    _sql_names = ["JSONB_CONTAINS"]
3866
3867
3868class JSONExtract(Binary, Func):
3869    _sql_names = ["JSON_EXTRACT"]
3870
3871
3872class JSONExtractScalar(JSONExtract):
3873    _sql_names = ["JSON_EXTRACT_SCALAR"]
3874
3875
3876class JSONBExtract(JSONExtract):
3877    _sql_names = ["JSONB_EXTRACT"]
3878
3879
3880class JSONBExtractScalar(JSONExtract):
3881    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3882
3883
3884class JSONFormat(Func):
3885    arg_types = {"this": False, "options": False}
3886    _sql_names = ["JSON_FORMAT"]
3887
3888
3889class Least(Func):
3890    arg_types = {"expressions": False}
3891    is_var_len_args = True
3892
3893
3894class Length(Func):
3895    pass
3896
3897
3898class Levenshtein(Func):
3899    arg_types = {
3900        "this": True,
3901        "expression": False,
3902        "ins_cost": False,
3903        "del_cost": False,
3904        "sub_cost": False,
3905    }
3906
3907
3908class Ln(Func):
3909    pass
3910
3911
3912class Log(Func):
3913    arg_types = {"this": True, "expression": False}
3914
3915
3916class Log2(Func):
3917    pass
3918
3919
3920class Log10(Func):
3921    pass
3922
3923
3924class LogicalOr(AggFunc):
3925    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3926
3927
3928class LogicalAnd(AggFunc):
3929    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3930
3931
3932class Lower(Func):
3933    _sql_names = ["LOWER", "LCASE"]
3934
3935
3936class Map(Func):
3937    arg_types = {"keys": False, "values": False}
3938
3939
3940class StarMap(Func):
3941    pass
3942
3943
3944class VarMap(Func):
3945    arg_types = {"keys": True, "values": True}
3946    is_var_len_args = True
3947
3948
3949# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
3950class MatchAgainst(Func):
3951    arg_types = {"this": True, "expressions": True, "modifier": False}
3952
3953
3954class Max(AggFunc):
3955    arg_types = {"this": True, "expressions": False}
3956    is_var_len_args = True
3957
3958
3959class MD5(Func):
3960    _sql_names = ["MD5"]
3961
3962
3963class Min(AggFunc):
3964    arg_types = {"this": True, "expressions": False}
3965    is_var_len_args = True
3966
3967
3968class Month(Func):
3969    pass
3970
3971
3972class Nvl2(Func):
3973    arg_types = {"this": True, "true": True, "false": False}
3974
3975
3976class Posexplode(Func):
3977    pass
3978
3979
3980class Pow(Binary, Func):
3981    _sql_names = ["POWER", "POW"]
3982
3983
3984class PercentileCont(AggFunc):
3985    arg_types = {"this": True, "expression": False}
3986
3987
3988class PercentileDisc(AggFunc):
3989    arg_types = {"this": True, "expression": False}
3990
3991
3992class Quantile(AggFunc):
3993    arg_types = {"this": True, "quantile": True}
3994
3995
3996# Clickhouse-specific:
3997# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
3998class Quantiles(AggFunc):
3999    arg_types = {"parameters": True, "expressions": True}
4000    is_var_len_args = True
4001
4002
4003class QuantileIf(AggFunc):
4004    arg_types = {"parameters": True, "expressions": True}
4005
4006
4007class ApproxQuantile(Quantile):
4008    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4009
4010
4011class RangeN(Func):
4012    arg_types = {"this": True, "expressions": True, "each": False}
4013
4014
4015class ReadCSV(Func):
4016    _sql_names = ["READ_CSV"]
4017    is_var_len_args = True
4018    arg_types = {"this": True, "expressions": False}
4019
4020
4021class Reduce(Func):
4022    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4023
4024
4025class RegexpExtract(Func):
4026    arg_types = {
4027        "this": True,
4028        "expression": True,
4029        "position": False,
4030        "occurrence": False,
4031        "group": False,
4032    }
4033
4034
4035class RegexpLike(Func):
4036    arg_types = {"this": True, "expression": True, "flag": False}
4037
4038
4039class RegexpILike(Func):
4040    arg_types = {"this": True, "expression": True, "flag": False}
4041
4042
4043# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4044# limit is the number of times a pattern is applied
4045class RegexpSplit(Func):
4046    arg_types = {"this": True, "expression": True, "limit": False}
4047
4048
4049class Repeat(Func):
4050    arg_types = {"this": True, "times": True}
4051
4052
4053class Round(Func):
4054    arg_types = {"this": True, "decimals": False}
4055
4056
4057class RowNumber(Func):
4058    arg_types: t.Dict[str, t.Any] = {}
4059
4060
4061class SafeDivide(Func):
4062    arg_types = {"this": True, "expression": True}
4063
4064
4065class SetAgg(AggFunc):
4066    pass
4067
4068
4069class SHA(Func):
4070    _sql_names = ["SHA", "SHA1"]
4071
4072
4073class SHA2(Func):
4074    _sql_names = ["SHA2"]
4075    arg_types = {"this": True, "length": False}
4076
4077
4078class SortArray(Func):
4079    arg_types = {"this": True, "asc": False}
4080
4081
4082class Split(Func):
4083    arg_types = {"this": True, "expression": True, "limit": False}
4084
4085
4086# Start may be omitted in the case of postgres
4087# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4088class Substring(Func):
4089    arg_types = {"this": True, "start": False, "length": False}
4090
4091
4092class StrPosition(Func):
4093    arg_types = {
4094        "this": True,
4095        "substr": True,
4096        "position": False,
4097        "instance": False,
4098    }
4099
4100
4101class StrToDate(Func):
4102    arg_types = {"this": True, "format": True}
4103
4104
4105class StrToTime(Func):
4106    arg_types = {"this": True, "format": True}
4107
4108
4109# Spark allows unix_timestamp()
4110# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4111class StrToUnix(Func):
4112    arg_types = {"this": False, "format": False}
4113
4114
4115class NumberToStr(Func):
4116    arg_types = {"this": True, "format": True}
4117
4118
4119class Struct(Func):
4120    arg_types = {"expressions": True}
4121    is_var_len_args = True
4122
4123
4124class StructExtract(Func):
4125    arg_types = {"this": True, "expression": True}
4126
4127
4128class Sum(AggFunc):
4129    pass
4130
4131
4132class Sqrt(Func):
4133    pass
4134
4135
4136class Stddev(AggFunc):
4137    pass
4138
4139
4140class StddevPop(AggFunc):
4141    pass
4142
4143
4144class StddevSamp(AggFunc):
4145    pass
4146
4147
4148class TimeToStr(Func):
4149    arg_types = {"this": True, "format": True}
4150
4151
4152class TimeToTimeStr(Func):
4153    pass
4154
4155
4156class TimeToUnix(Func):
4157    pass
4158
4159
4160class TimeStrToDate(Func):
4161    pass
4162
4163
4164class TimeStrToTime(Func):
4165    pass
4166
4167
4168class TimeStrToUnix(Func):
4169    pass
4170
4171
4172class Trim(Func):
4173    arg_types = {
4174        "this": True,
4175        "expression": False,
4176        "position": False,
4177        "collation": False,
4178    }
4179
4180
4181class TsOrDsAdd(Func, TimeUnit):
4182    arg_types = {"this": True, "expression": True, "unit": False}
4183
4184
4185class TsOrDsToDateStr(Func):
4186    pass
4187
4188
4189class TsOrDsToDate(Func):
4190    arg_types = {"this": True, "format": False}
4191
4192
4193class TsOrDiToDi(Func):
4194    pass
4195
4196
4197class Unhex(Func):
4198    pass
4199
4200
4201class UnixToStr(Func):
4202    arg_types = {"this": True, "format": False}
4203
4204
4205# https://prestodb.io/docs/current/functions/datetime.html
4206# presto has weird zone/hours/minutes
4207class UnixToTime(Func):
4208    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4209
4210    SECONDS = Literal.string("seconds")
4211    MILLIS = Literal.string("millis")
4212    MICROS = Literal.string("micros")
4213
4214
4215class UnixToTimeStr(Func):
4216    pass
4217
4218
4219class Upper(Func):
4220    _sql_names = ["UPPER", "UCASE"]
4221
4222
4223class Variance(AggFunc):
4224    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4225
4226
4227class VariancePop(AggFunc):
4228    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4229
4230
4231class Week(Func):
4232    arg_types = {"this": True, "mode": False}
4233
4234
4235class XMLTable(Func):
4236    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4237
4238
4239class Year(Func):
4240    pass
4241
4242
4243class Use(Expression):
4244    arg_types = {"this": True, "kind": False}
4245
4246
4247class Merge(Expression):
4248    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4249
4250
4251class When(Func):
4252    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4253
4254
4255# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4256# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4257class NextValueFor(Func):
4258    arg_types = {"this": True, "order": False}
4259
4260
4261def _norm_arg(arg):
4262    return arg.lower() if type(arg) is str else arg
4263
4264
4265ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4266
4267
4268# Helpers
4269@t.overload
4270def maybe_parse(
4271    sql_or_expression: ExpOrStr,
4272    *,
4273    into: t.Type[E],
4274    dialect: DialectType = None,
4275    prefix: t.Optional[str] = None,
4276    copy: bool = False,
4277    **opts,
4278) -> E:
4279    ...
4280
4281
4282@t.overload
4283def maybe_parse(
4284    sql_or_expression: str | E,
4285    *,
4286    into: t.Optional[IntoType] = None,
4287    dialect: DialectType = None,
4288    prefix: t.Optional[str] = None,
4289    copy: bool = False,
4290    **opts,
4291) -> E:
4292    ...
4293
4294
4295def maybe_parse(
4296    sql_or_expression: ExpOrStr,
4297    *,
4298    into: t.Optional[IntoType] = None,
4299    dialect: DialectType = None,
4300    prefix: t.Optional[str] = None,
4301    copy: bool = False,
4302    **opts,
4303) -> Expression:
4304    """Gracefully handle a possible string or expression.
4305
4306    Example:
4307        >>> maybe_parse("1")
4308        (LITERAL this: 1, is_string: False)
4309        >>> maybe_parse(to_identifier("x"))
4310        (IDENTIFIER this: x, quoted: False)
4311
4312    Args:
4313        sql_or_expression: the SQL code string or an expression
4314        into: the SQLGlot Expression to parse into
4315        dialect: the dialect used to parse the input expressions (in the case that an
4316            input expression is a SQL string).
4317        prefix: a string to prefix the sql with before it gets parsed
4318            (automatically includes a space)
4319        copy: whether or not to copy the expression.
4320        **opts: other options to use to parse the input expressions (again, in the case
4321            that an input expression is a SQL string).
4322
4323    Returns:
4324        Expression: the parsed or given expression.
4325    """
4326    if isinstance(sql_or_expression, Expression):
4327        if copy:
4328            return sql_or_expression.copy()
4329        return sql_or_expression
4330
4331    import sqlglot
4332
4333    sql = str(sql_or_expression)
4334    if prefix:
4335        sql = f"{prefix} {sql}"
4336    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4337
4338
4339def _maybe_copy(instance, copy=True):
4340    return instance.copy() if copy else instance
4341
4342
4343def _is_wrong_expression(expression, into):
4344    return isinstance(expression, Expression) and not isinstance(expression, into)
4345
4346
4347def _apply_builder(
4348    expression,
4349    instance,
4350    arg,
4351    copy=True,
4352    prefix=None,
4353    into=None,
4354    dialect=None,
4355    **opts,
4356):
4357    if _is_wrong_expression(expression, into):
4358        expression = into(this=expression)
4359    instance = _maybe_copy(instance, copy)
4360    expression = maybe_parse(
4361        sql_or_expression=expression,
4362        prefix=prefix,
4363        into=into,
4364        dialect=dialect,
4365        **opts,
4366    )
4367    instance.set(arg, expression)
4368    return instance
4369
4370
4371def _apply_child_list_builder(
4372    *expressions,
4373    instance,
4374    arg,
4375    append=True,
4376    copy=True,
4377    prefix=None,
4378    into=None,
4379    dialect=None,
4380    properties=None,
4381    **opts,
4382):
4383    instance = _maybe_copy(instance, copy)
4384    parsed = []
4385    for expression in expressions:
4386        if _is_wrong_expression(expression, into):
4387            expression = into(expressions=[expression])
4388        expression = maybe_parse(
4389            expression,
4390            into=into,
4391            dialect=dialect,
4392            prefix=prefix,
4393            **opts,
4394        )
4395        parsed.extend(expression.expressions)
4396
4397    existing = instance.args.get(arg)
4398    if append and existing:
4399        parsed = existing.expressions + parsed
4400
4401    child = into(expressions=parsed)
4402    for k, v in (properties or {}).items():
4403        child.set(k, v)
4404    instance.set(arg, child)
4405    return instance
4406
4407
4408def _apply_list_builder(
4409    *expressions,
4410    instance,
4411    arg,
4412    append=True,
4413    copy=True,
4414    prefix=None,
4415    into=None,
4416    dialect=None,
4417    **opts,
4418):
4419    inst = _maybe_copy(instance, copy)
4420
4421    expressions = [
4422        maybe_parse(
4423            sql_or_expression=expression,
4424            into=into,
4425            prefix=prefix,
4426            dialect=dialect,
4427            **opts,
4428        )
4429        for expression in expressions
4430    ]
4431
4432    existing_expressions = inst.args.get(arg)
4433    if append and existing_expressions:
4434        expressions = existing_expressions + expressions
4435
4436    inst.set(arg, expressions)
4437    return inst
4438
4439
4440def _apply_conjunction_builder(
4441    *expressions,
4442    instance,
4443    arg,
4444    into=None,
4445    append=True,
4446    copy=True,
4447    dialect=None,
4448    **opts,
4449):
4450    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4451    if not expressions:
4452        return instance
4453
4454    inst = _maybe_copy(instance, copy)
4455
4456    existing = inst.args.get(arg)
4457    if append and existing is not None:
4458        expressions = [existing.this if into else existing] + list(expressions)
4459
4460    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4461
4462    inst.set(arg, into(this=node) if into else node)
4463    return inst
4464
4465
4466def _combine(expressions, operator, dialect=None, copy=True, **opts):
4467    expressions = [
4468        condition(expression, dialect=dialect, copy=copy, **opts) for expression in expressions
4469    ]
4470    this = expressions[0]
4471    if expressions[1:]:
4472        this = _wrap(this, Connector)
4473    for expression in expressions[1:]:
4474        this = operator(this=this, expression=_wrap(expression, Connector))
4475    return this
4476
4477
4478def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4479    if isinstance(expression, kind):
4480        return Paren(this=expression)
4481    return expression
4482
4483
4484def union(left, right, distinct=True, dialect=None, **opts):
4485    """
4486    Initializes a syntax tree from one UNION expression.
4487
4488    Example:
4489        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4490        'SELECT * FROM foo UNION SELECT * FROM bla'
4491
4492    Args:
4493        left (str | Expression): the SQL code string corresponding to the left-hand side.
4494            If an `Expression` instance is passed, it will be used as-is.
4495        right (str | Expression): the SQL code string corresponding to the right-hand side.
4496            If an `Expression` instance is passed, it will be used as-is.
4497        distinct (bool): set the DISTINCT flag if and only if this is true.
4498        dialect (str): the dialect used to parse the input expression.
4499        opts (kwargs): other options to use to parse the input expressions.
4500    Returns:
4501        Union: the syntax tree for the UNION expression.
4502    """
4503    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4504    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4505
4506    return Union(this=left, expression=right, distinct=distinct)
4507
4508
4509def intersect(left, right, distinct=True, dialect=None, **opts):
4510    """
4511    Initializes a syntax tree from one INTERSECT expression.
4512
4513    Example:
4514        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4515        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4516
4517    Args:
4518        left (str | Expression): the SQL code string corresponding to the left-hand side.
4519            If an `Expression` instance is passed, it will be used as-is.
4520        right (str | Expression): the SQL code string corresponding to the right-hand side.
4521            If an `Expression` instance is passed, it will be used as-is.
4522        distinct (bool): set the DISTINCT flag if and only if this is true.
4523        dialect (str): the dialect used to parse the input expression.
4524        opts (kwargs): other options to use to parse the input expressions.
4525    Returns:
4526        Intersect: the syntax tree for the INTERSECT expression.
4527    """
4528    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4529    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4530
4531    return Intersect(this=left, expression=right, distinct=distinct)
4532
4533
4534def except_(left, right, distinct=True, dialect=None, **opts):
4535    """
4536    Initializes a syntax tree from one EXCEPT expression.
4537
4538    Example:
4539        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4540        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4541
4542    Args:
4543        left (str | Expression): the SQL code string corresponding to the left-hand side.
4544            If an `Expression` instance is passed, it will be used as-is.
4545        right (str | Expression): the SQL code string corresponding to the right-hand side.
4546            If an `Expression` instance is passed, it will be used as-is.
4547        distinct (bool): set the DISTINCT flag if and only if this is true.
4548        dialect (str): the dialect used to parse the input expression.
4549        opts (kwargs): other options to use to parse the input expressions.
4550    Returns:
4551        Except: the syntax tree for the EXCEPT statement.
4552    """
4553    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4554    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4555
4556    return Except(this=left, expression=right, distinct=distinct)
4557
4558
4559def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4560    """
4561    Initializes a syntax tree from one or multiple SELECT expressions.
4562
4563    Example:
4564        >>> select("col1", "col2").from_("tbl").sql()
4565        'SELECT col1, col2 FROM tbl'
4566
4567    Args:
4568        *expressions: the SQL code string to parse as the expressions of a
4569            SELECT statement. If an Expression instance is passed, this is used as-is.
4570        dialect: the dialect used to parse the input expressions (in the case that an
4571            input expression is a SQL string).
4572        **opts: other options to use to parse the input expressions (again, in the case
4573            that an input expression is a SQL string).
4574
4575    Returns:
4576        Select: the syntax tree for the SELECT statement.
4577    """
4578    return Select().select(*expressions, dialect=dialect, **opts)
4579
4580
4581def from_(*expressions, dialect=None, **opts) -> Select:
4582    """
4583    Initializes a syntax tree from a FROM expression.
4584
4585    Example:
4586        >>> from_("tbl").select("col1", "col2").sql()
4587        'SELECT col1, col2 FROM tbl'
4588
4589    Args:
4590        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4591            SELECT statement. If an Expression instance is passed, this is used as-is.
4592        dialect (str): the dialect used to parse the input expression (in the case that the
4593            input expression is a SQL string).
4594        **opts: other options to use to parse the input expressions (again, in the case
4595            that the input expression is a SQL string).
4596
4597    Returns:
4598        Select: the syntax tree for the SELECT statement.
4599    """
4600    return Select().from_(*expressions, dialect=dialect, **opts)
4601
4602
4603def update(
4604    table: str | Table,
4605    properties: dict,
4606    where: t.Optional[ExpOrStr] = None,
4607    from_: t.Optional[ExpOrStr] = None,
4608    dialect: DialectType = None,
4609    **opts,
4610) -> Update:
4611    """
4612    Creates an update statement.
4613
4614    Example:
4615        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4616        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4617
4618    Args:
4619        *properties: dictionary of properties to set which are
4620            auto converted to sql objects eg None -> NULL
4621        where: sql conditional parsed into a WHERE statement
4622        from_: sql statement parsed into a FROM statement
4623        dialect: the dialect used to parse the input expressions.
4624        **opts: other options to use to parse the input expressions.
4625
4626    Returns:
4627        Update: the syntax tree for the UPDATE statement.
4628    """
4629    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4630    update_expr.set(
4631        "expressions",
4632        [
4633            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4634            for k, v in properties.items()
4635        ],
4636    )
4637    if from_:
4638        update_expr.set(
4639            "from",
4640            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4641        )
4642    if isinstance(where, Condition):
4643        where = Where(this=where)
4644    if where:
4645        update_expr.set(
4646            "where",
4647            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4648        )
4649    return update_expr
4650
4651
4652def delete(
4653    table: ExpOrStr,
4654    where: t.Optional[ExpOrStr] = None,
4655    returning: t.Optional[ExpOrStr] = None,
4656    dialect: DialectType = None,
4657    **opts,
4658) -> Delete:
4659    """
4660    Builds a delete statement.
4661
4662    Example:
4663        >>> delete("my_table", where="id > 1").sql()
4664        'DELETE FROM my_table WHERE id > 1'
4665
4666    Args:
4667        where: sql conditional parsed into a WHERE statement
4668        returning: sql conditional parsed into a RETURNING statement
4669        dialect: the dialect used to parse the input expressions.
4670        **opts: other options to use to parse the input expressions.
4671
4672    Returns:
4673        Delete: the syntax tree for the DELETE statement.
4674    """
4675    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4676    if where:
4677        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4678    if returning:
4679        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4680    return delete_expr
4681
4682
4683def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4684    """
4685    Initialize a logical condition expression.
4686
4687    Example:
4688        >>> condition("x=1").sql()
4689        'x = 1'
4690
4691        This is helpful for composing larger logical syntax trees:
4692        >>> where = condition("x=1")
4693        >>> where = where.and_("y=1")
4694        >>> Select().from_("tbl").select("*").where(where).sql()
4695        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4696
4697    Args:
4698        *expression (str | Expression): the SQL code string to parse.
4699            If an Expression instance is passed, this is used as-is.
4700        dialect (str): the dialect used to parse the input expression (in the case that the
4701            input expression is a SQL string).
4702        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4703        **opts: other options to use to parse the input expressions (again, in the case
4704            that the input expression is a SQL string).
4705
4706    Returns:
4707        Condition: the expression
4708    """
4709    return maybe_parse(  # type: ignore
4710        expression,
4711        into=Condition,
4712        dialect=dialect,
4713        copy=copy,
4714        **opts,
4715    )
4716
4717
4718def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4719    """
4720    Combine multiple conditions with an AND logical operator.
4721
4722    Example:
4723        >>> and_("x=1", and_("y=1", "z=1")).sql()
4724        'x = 1 AND (y = 1 AND z = 1)'
4725
4726    Args:
4727        *expressions (str | Expression): the SQL code strings to parse.
4728            If an Expression instance is passed, this is used as-is.
4729        dialect (str): the dialect used to parse the input expression.
4730        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4731        **opts: other options to use to parse the input expressions.
4732
4733    Returns:
4734        And: the new condition
4735    """
4736    return _combine(expressions, And, dialect, copy=copy, **opts)
4737
4738
4739def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4740    """
4741    Combine multiple conditions with an OR logical operator.
4742
4743    Example:
4744        >>> or_("x=1", or_("y=1", "z=1")).sql()
4745        'x = 1 OR (y = 1 OR z = 1)'
4746
4747    Args:
4748        *expressions (str | Expression): the SQL code strings to parse.
4749            If an Expression instance is passed, this is used as-is.
4750        dialect (str): the dialect used to parse the input expression.
4751        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4752        **opts: other options to use to parse the input expressions.
4753
4754    Returns:
4755        Or: the new condition
4756    """
4757    return _combine(expressions, Or, dialect, copy=copy, **opts)
4758
4759
4760def not_(expression, dialect=None, copy=True, **opts) -> Not:
4761    """
4762    Wrap a condition with a NOT operator.
4763
4764    Example:
4765        >>> not_("this_suit='black'").sql()
4766        "NOT this_suit = 'black'"
4767
4768    Args:
4769        expression (str | Expression): the SQL code strings to parse.
4770            If an Expression instance is passed, this is used as-is.
4771        dialect (str): the dialect used to parse the input expression.
4772        **opts: other options to use to parse the input expressions.
4773
4774    Returns:
4775        Not: the new condition
4776    """
4777    this = condition(
4778        expression,
4779        dialect=dialect,
4780        copy=copy,
4781        **opts,
4782    )
4783    return Not(this=_wrap(this, Connector))
4784
4785
4786def paren(expression, copy=True) -> Paren:
4787    return Paren(this=_maybe_copy(expression, copy))
4788
4789
4790SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4791
4792
4793@t.overload
4794def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None:
4795    ...
4796
4797
4798@t.overload
4799def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier:
4800    ...
4801
4802
4803def to_identifier(name, quoted=None):
4804    """Builds an identifier.
4805
4806    Args:
4807        name: The name to turn into an identifier.
4808        quoted: Whether or not force quote the identifier.
4809
4810    Returns:
4811        The identifier ast node.
4812    """
4813
4814    if name is None:
4815        return None
4816
4817    if isinstance(name, Identifier):
4818        identifier = name
4819    elif isinstance(name, str):
4820        identifier = Identifier(
4821            this=name,
4822            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4823        )
4824    else:
4825        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4826    return identifier
4827
4828
4829INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4830
4831
4832def to_interval(interval: str | Literal) -> Interval:
4833    """Builds an interval expression from a string like '1 day' or '5 months'."""
4834    if isinstance(interval, Literal):
4835        if not interval.is_string:
4836            raise ValueError("Invalid interval string.")
4837
4838        interval = interval.this
4839
4840    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4841
4842    if not interval_parts:
4843        raise ValueError("Invalid interval string.")
4844
4845    return Interval(
4846        this=Literal.string(interval_parts.group(1)),
4847        unit=Var(this=interval_parts.group(2)),
4848    )
4849
4850
4851@t.overload
4852def to_table(sql_path: str | Table, **kwargs) -> Table:
4853    ...
4854
4855
4856@t.overload
4857def to_table(sql_path: None, **kwargs) -> None:
4858    ...
4859
4860
4861def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4862    """
4863    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4864    If a table is passed in then that table is returned.
4865
4866    Args:
4867        sql_path: a `[catalog].[schema].[table]` string.
4868
4869    Returns:
4870        A table expression.
4871    """
4872    if sql_path is None or isinstance(sql_path, Table):
4873        return sql_path
4874    if not isinstance(sql_path, str):
4875        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4876
4877    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4878    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4879
4880
4881def to_column(sql_path: str | Column, **kwargs) -> Column:
4882    """
4883    Create a column from a `[table].[column]` sql path. Schema is optional.
4884
4885    If a column is passed in then that column is returned.
4886
4887    Args:
4888        sql_path: `[table].[column]` string
4889    Returns:
4890        Table: A column expression
4891    """
4892    if sql_path is None or isinstance(sql_path, Column):
4893        return sql_path
4894    if not isinstance(sql_path, str):
4895        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4896    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4897
4898
4899def alias_(
4900    expression: ExpOrStr,
4901    alias: str | Identifier,
4902    table: bool | t.Sequence[str | Identifier] = False,
4903    quoted: t.Optional[bool] = None,
4904    dialect: DialectType = None,
4905    **opts,
4906):
4907    """Create an Alias expression.
4908
4909    Example:
4910        >>> alias_('foo', 'bar').sql()
4911        'foo AS bar'
4912
4913        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4914        '(SELECT 1, 2) AS bar(a, b)'
4915
4916    Args:
4917        expression: the SQL code strings to parse.
4918            If an Expression instance is passed, this is used as-is.
4919        alias: the alias name to use. If the name has
4920            special characters it is quoted.
4921        table: Whether or not to create a table alias, can also be a list of columns.
4922        quoted: whether or not to quote the alias
4923        dialect: the dialect used to parse the input expression.
4924        **opts: other options to use to parse the input expressions.
4925
4926    Returns:
4927        Alias: the aliased expression
4928    """
4929    exp = maybe_parse(expression, dialect=dialect, **opts)
4930    alias = to_identifier(alias, quoted=quoted)
4931
4932    if table:
4933        table_alias = TableAlias(this=alias)
4934
4935        exp = exp.copy() if isinstance(expression, Expression) else exp
4936        exp.set("alias", table_alias)
4937
4938        if not isinstance(table, bool):
4939            for column in table:
4940                table_alias.append("columns", to_identifier(column, quoted=quoted))
4941
4942        return exp
4943
4944    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4945    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4946    # for the complete Window expression.
4947    #
4948    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4949
4950    if "alias" in exp.arg_types and not isinstance(exp, Window):
4951        exp = exp.copy()
4952        exp.set("alias", alias)
4953        return exp
4954    return Alias(this=exp, alias=alias)
4955
4956
4957def subquery(expression, alias=None, dialect=None, **opts):
4958    """
4959    Build a subquery expression.
4960
4961    Example:
4962        >>> subquery('select x from tbl', 'bar').select('x').sql()
4963        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4964
4965    Args:
4966        expression (str | Expression): the SQL code strings to parse.
4967            If an Expression instance is passed, this is used as-is.
4968        alias (str | Expression): the alias name to use.
4969        dialect (str): the dialect used to parse the input expression.
4970        **opts: other options to use to parse the input expressions.
4971
4972    Returns:
4973        Select: a new select with the subquery expression included
4974    """
4975
4976    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4977    return Select().from_(expression, dialect=dialect, **opts)
4978
4979
4980def column(
4981    col: str | Identifier,
4982    table: t.Optional[str | Identifier] = None,
4983    db: t.Optional[str | Identifier] = None,
4984    catalog: t.Optional[str | Identifier] = None,
4985    quoted: t.Optional[bool] = None,
4986) -> Column:
4987    """
4988    Build a Column.
4989
4990    Args:
4991        col: column name
4992        table: table name
4993        db: db name
4994        catalog: catalog name
4995        quoted: whether or not to force quote each part
4996    Returns:
4997        Column: column instance
4998    """
4999    return Column(
5000        this=to_identifier(col, quoted=quoted),
5001        table=to_identifier(table, quoted=quoted),
5002        db=to_identifier(db, quoted=quoted),
5003        catalog=to_identifier(catalog, quoted=quoted),
5004    )
5005
5006
5007def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5008    """Cast an expression to a data type.
5009
5010    Example:
5011        >>> cast('x + 1', 'int').sql()
5012        'CAST(x + 1 AS INT)'
5013
5014    Args:
5015        expression: The expression to cast.
5016        to: The datatype to cast to.
5017
5018    Returns:
5019        A cast node.
5020    """
5021    expression = maybe_parse(expression, **opts)
5022    return Cast(this=expression, to=DataType.build(to, **opts))
5023
5024
5025def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5026    """Build a Table.
5027
5028    Args:
5029        table (str | Expression): column name
5030        db (str | Expression): db name
5031        catalog (str | Expression): catalog name
5032
5033    Returns:
5034        Table: table instance
5035    """
5036    return Table(
5037        this=to_identifier(table, quoted=quoted),
5038        db=to_identifier(db, quoted=quoted),
5039        catalog=to_identifier(catalog, quoted=quoted),
5040        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5041    )
5042
5043
5044def values(
5045    values: t.Iterable[t.Tuple[t.Any, ...]],
5046    alias: t.Optional[str] = None,
5047    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5048) -> Values:
5049    """Build VALUES statement.
5050
5051    Example:
5052        >>> values([(1, '2')]).sql()
5053        "VALUES (1, '2')"
5054
5055    Args:
5056        values: values statements that will be converted to SQL
5057        alias: optional alias
5058        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5059         If either are provided then an alias is also required.
5060
5061    Returns:
5062        Values: the Values expression object
5063    """
5064    if columns and not alias:
5065        raise ValueError("Alias is required when providing columns")
5066
5067    return Values(
5068        expressions=[convert(tup) for tup in values],
5069        alias=(
5070            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5071            if columns
5072            else (TableAlias(this=to_identifier(alias)) if alias else None)
5073        ),
5074    )
5075
5076
5077def var(name: t.Optional[ExpOrStr]) -> Var:
5078    """Build a SQL variable.
5079
5080    Example:
5081        >>> repr(var('x'))
5082        '(VAR this: x)'
5083
5084        >>> repr(var(column('x', table='y')))
5085        '(VAR this: x)'
5086
5087    Args:
5088        name: The name of the var or an expression who's name will become the var.
5089
5090    Returns:
5091        The new variable node.
5092    """
5093    if not name:
5094        raise ValueError("Cannot convert empty name into var.")
5095
5096    if isinstance(name, Expression):
5097        name = name.name
5098    return Var(this=name)
5099
5100
5101def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5102    """Build ALTER TABLE... RENAME... expression
5103
5104    Args:
5105        old_name: The old name of the table
5106        new_name: The new name of the table
5107
5108    Returns:
5109        Alter table expression
5110    """
5111    old_table = to_table(old_name)
5112    new_table = to_table(new_name)
5113    return AlterTable(
5114        this=old_table,
5115        actions=[
5116            RenameTable(this=new_table),
5117        ],
5118    )
5119
5120
5121def convert(value: t.Any, copy: bool = False) -> Expression:
5122    """Convert a python value into an expression object.
5123
5124    Raises an error if a conversion is not possible.
5125
5126    Args:
5127        value: A python object.
5128        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5129
5130    Returns:
5131        Expression: the equivalent expression object.
5132    """
5133    if isinstance(value, Expression):
5134        return _maybe_copy(value, copy)
5135    if isinstance(value, str):
5136        return Literal.string(value)
5137    if isinstance(value, bool):
5138        return Boolean(this=value)
5139    if value is None or (isinstance(value, float) and math.isnan(value)):
5140        return NULL
5141    if isinstance(value, numbers.Number):
5142        return Literal.number(value)
5143    if isinstance(value, datetime.datetime):
5144        datetime_literal = Literal.string(
5145            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5146        )
5147        return TimeStrToTime(this=datetime_literal)
5148    if isinstance(value, datetime.date):
5149        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5150        return DateStrToDate(this=date_literal)
5151    if isinstance(value, tuple):
5152        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5153    if isinstance(value, list):
5154        return Array(expressions=[convert(v, copy=copy) for v in value])
5155    if isinstance(value, dict):
5156        return Map(
5157            keys=[convert(k, copy=copy) for k in value],
5158            values=[convert(v, copy=copy) for v in value.values()],
5159        )
5160    raise ValueError(f"Cannot convert {value}")
5161
5162
5163def replace_children(expression, fun, *args, **kwargs):
5164    """
5165    Replace children of an expression with the result of a lambda fun(child) -> exp.
5166    """
5167    for k, v in expression.args.items():
5168        is_list_arg = type(v) is list
5169
5170        child_nodes = v if is_list_arg else [v]
5171        new_child_nodes = []
5172
5173        for cn in child_nodes:
5174            if isinstance(cn, Expression):
5175                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5176                    new_child_nodes.append(child_node)
5177                    child_node.parent = expression
5178                    child_node.arg_key = k
5179            else:
5180                new_child_nodes.append(cn)
5181
5182        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5183
5184
5185def column_table_names(expression):
5186    """
5187    Return all table names referenced through columns in an expression.
5188
5189    Example:
5190        >>> import sqlglot
5191        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5192        ['c', 'a']
5193
5194    Args:
5195        expression (sqlglot.Expression): expression to find table names
5196
5197    Returns:
5198        list: A list of unique names
5199    """
5200    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
5201
5202
5203def table_name(table) -> str:
5204    """Get the full name of a table as a string.
5205
5206    Args:
5207        table (exp.Table | str): table expression node or string.
5208
5209    Examples:
5210        >>> from sqlglot import exp, parse_one
5211        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5212        'a.b.c'
5213
5214    Returns:
5215        The table name.
5216    """
5217
5218    table = maybe_parse(table, into=Table)
5219
5220    if not table:
5221        raise ValueError(f"Cannot parse {table}")
5222
5223    return ".".join(
5224        part
5225        for part in (
5226            table.text("catalog"),
5227            table.text("db"),
5228            table.name,
5229        )
5230        if part
5231    )
5232
5233
5234def replace_tables(expression, mapping):
5235    """Replace all tables in expression according to the mapping.
5236
5237    Args:
5238        expression (sqlglot.Expression): expression node to be transformed and replaced.
5239        mapping (Dict[str, str]): mapping of table names.
5240
5241    Examples:
5242        >>> from sqlglot import exp, parse_one
5243        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5244        'SELECT * FROM c'
5245
5246    Returns:
5247        The mapped expression.
5248    """
5249
5250    def _replace_tables(node):
5251        if isinstance(node, Table):
5252            new_name = mapping.get(table_name(node))
5253            if new_name:
5254                return to_table(
5255                    new_name,
5256                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5257                )
5258        return node
5259
5260    return expression.transform(_replace_tables)
5261
5262
5263def replace_placeholders(expression, *args, **kwargs):
5264    """Replace placeholders in an expression.
5265
5266    Args:
5267        expression (sqlglot.Expression): expression node to be transformed and replaced.
5268        args: positional names that will substitute unnamed placeholders in the given order.
5269        kwargs: keyword arguments that will substitute named placeholders.
5270
5271    Examples:
5272        >>> from sqlglot import exp, parse_one
5273        >>> replace_placeholders(
5274        ...     parse_one("select * from :tbl where ? = ?"),
5275        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5276        ... ).sql()
5277        "SELECT * FROM foo WHERE str_col = 'b'"
5278
5279    Returns:
5280        The mapped expression.
5281    """
5282
5283    def _replace_placeholders(node, args, **kwargs):
5284        if isinstance(node, Placeholder):
5285            if node.name:
5286                new_name = kwargs.get(node.name)
5287                if new_name:
5288                    return convert(new_name)
5289            else:
5290                try:
5291                    return convert(next(args))
5292                except StopIteration:
5293                    pass
5294        return node
5295
5296    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5297
5298
5299def expand(
5300    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5301) -> Expression:
5302    """Transforms an expression by expanding all referenced sources into subqueries.
5303
5304    Examples:
5305        >>> from sqlglot import parse_one
5306        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5307        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5308
5309        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5310        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5311
5312    Args:
5313        expression: The expression to expand.
5314        sources: A dictionary of name to Subqueryables.
5315        copy: Whether or not to copy the expression during transformation. Defaults to True.
5316
5317    Returns:
5318        The transformed expression.
5319    """
5320
5321    def _expand(node: Expression):
5322        if isinstance(node, Table):
5323            name = table_name(node)
5324            source = sources.get(name)
5325            if source:
5326                subquery = source.subquery(node.alias or name)
5327                subquery.comments = [f"source: {name}"]
5328                return subquery.transform(_expand, copy=False)
5329        return node
5330
5331    return expression.transform(_expand, copy=copy)
5332
5333
5334def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5335    """
5336    Returns a Func expression.
5337
5338    Examples:
5339        >>> func("abs", 5).sql()
5340        'ABS(5)'
5341
5342        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5343        'CAST(5 AS DOUBLE)'
5344
5345    Args:
5346        name: the name of the function to build.
5347        args: the args used to instantiate the function of interest.
5348        dialect: the source dialect.
5349        kwargs: the kwargs used to instantiate the function of interest.
5350
5351    Note:
5352        The arguments `args` and `kwargs` are mutually exclusive.
5353
5354    Returns:
5355        An instance of the function of interest, or an anonymous function, if `name` doesn't
5356        correspond to an existing `sqlglot.expressions.Func` class.
5357    """
5358    if args and kwargs:
5359        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5360
5361    from sqlglot.dialects.dialect import Dialect
5362
5363    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5364    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5365
5366    parser = Dialect.get_or_raise(dialect)().parser()
5367    from_args_list = parser.FUNCTIONS.get(name.upper())
5368
5369    if from_args_list:
5370        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5371    else:
5372        kwargs = kwargs or {"expressions": converted}
5373        function = Anonymous(this=name, **kwargs)
5374
5375    for error_message in function.error_messages(converted):
5376        raise ValueError(error_message)
5377
5378    return function
5379
5380
5381def true():
5382    """
5383    Returns a true Boolean expression.
5384    """
5385    return Boolean(this=True)
5386
5387
5388def false():
5389    """
5390    Returns a false Boolean expression.
5391    """
5392    return Boolean(this=False)
5393
5394
5395def null():
5396    """
5397    Returns a Null expression.
5398    """
5399    return Null()
5400
5401
5402# TODO: deprecate this
5403TRUE = Boolean(this=True)
5404FALSE = Boolean(this=False)
5405NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68        parent: a reference to the parent expression (or None, in case of root expressions).
 69        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 70            uses to refer to it.
 71        comments: a list of comments that are associated with a given expression. This is used in
 72            order to preserve comments when transpiling SQL code.
 73        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 74            optimizer, in order to enable some transformations that require type information.
 75
 76    Example:
 77        >>> class Foo(Expression):
 78        ...     arg_types = {"this": True, "expression": False}
 79
 80        The above definition informs us that Foo is an Expression that requires an argument called
 81        "this" and may also optionally receive an argument called "expression".
 82
 83    Args:
 84        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
263        if self.comments is None:
264            self.comments = []
265        if comments:
266            self.comments.extend(comments)
267
268    def append(self, arg_key, value):
269        """
270        Appends value to arg_key if it's a list or sets it as a new list.
271
272        Args:
273            arg_key (str): name of the list expression arg
274            value (Any): value to append to the list
275        """
276        if not isinstance(self.args.get(arg_key), list):
277            self.args[arg_key] = []
278        self.args[arg_key].append(value)
279        self._set_parent(arg_key, value)
280
281    def set(self, arg_key, value):
282        """
283        Sets `arg_key` to `value`.
284
285        Args:
286            arg_key (str): name of the expression arg.
287            value: value to set the arg to.
288        """
289        self.args[arg_key] = value
290        self._set_parent(arg_key, value)
291
292    def _set_parent(self, arg_key, value):
293        if hasattr(value, "parent"):
294            value.parent = self
295            value.arg_key = arg_key
296        elif type(value) is list:
297            for v in value:
298                if hasattr(v, "parent"):
299                    v.parent = self
300                    v.arg_key = arg_key
301
302    @property
303    def depth(self):
304        """
305        Returns the depth of this tree.
306        """
307        if self.parent:
308            return self.parent.depth + 1
309        return 0
310
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    yield k, vs
321
322    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)
334
335    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression
349
350    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)
364
365    @property
366    def parent_select(self):
367        """
368        Returns the parent select statement.
369        """
370        return self.find_ancestor(Select)
371
372    @property
373    def same_parent(self):
374        """Returns if the parent is the same class as itself."""
375        return type(self.parent) is self.__class__
376
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression
385
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)
403
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)
419
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))
439
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression
448
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self
456
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())
462
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node
472
473    def __str__(self):
474        return self.sql()
475
476    def __repr__(self):
477        return self._to_s()
478
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)
493
494    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
495        indent = "" if not level else "\n"
496        indent += "".join(["  "] * level)
497        left = f"({self.key.upper()} "
498
499        args: t.Dict[str, t.Any] = {
500            k: ", ".join(
501                v._to_s(hide_missing=hide_missing, level=level + 1)
502                if hasattr(v, "_to_s")
503                else str(v)
504                for v in ensure_list(vs)
505                if v is not None
506            )
507            for k, vs in self.args.items()
508        }
509        args["comments"] = self.comments
510        args["type"] = self.type
511        args = {k: v for k, v in args.items() if v or not hide_missing}
512
513        right = ", ".join(f"{k}: {v}" for k, v in args.items())
514        right += ")"
515
516        return indent + left + right
517
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node
544
545    def replace(self, expression):
546        """
547        Swap out this expression with a new expression.
548
549        For example::
550
551            >>> tree = Select().select("x").from_("tbl")
552            >>> tree.find(Column).replace(Column(this="y"))
553            (COLUMN this: y)
554            >>> tree.sql()
555            'SELECT y FROM tbl'
556
557        Args:
558            expression (Expression|None): new node
559
560        Returns:
561            The new expression or expressions.
562        """
563        if not self.parent:
564            return expression
565
566        parent = self.parent
567        self.parent = None
568
569        replace_children(parent, lambda child: expression if child is self else child)
570        return expression
571
572    def pop(self):
573        """
574        Remove this expression from its AST.
575
576        Returns:
577            The popped expression.
578        """
579        self.replace(None)
580        return self
581
582    def assert_is(self, type_):
583        """
584        Assert that this `Expression` is an instance of `type_`.
585
586        If it is NOT an instance of `type_`, this raises an assertion error.
587        Otherwise, this returns this expression.
588
589        Examples:
590            This is useful for type security in chained expressions:
591
592            >>> import sqlglot
593            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
594            'SELECT x, z FROM y'
595        """
596        assert isinstance(self, type_)
597        return self
598
599    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
600        """
601        Checks if this expression is valid (e.g. all mandatory args are set).
602
603        Args:
604            args: a sequence of values that were used to instantiate a Func expression. This is used
605                to check that the provided arguments don't exceed the function argument limit.
606
607        Returns:
608            A list of error messages for all possible errors that were found.
609        """
610        errors: t.List[str] = []
611
612        for k in self.args:
613            if k not in self.arg_types:
614                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
615        for k, mandatory in self.arg_types.items():
616            v = self.args.get(k)
617            if mandatory and (v is None or (isinstance(v, list) and not v)):
618                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
619
620        if (
621            args
622            and isinstance(self, Func)
623            and len(args) > len(self.arg_types)
624            and not self.is_var_len_args
625        ):
626            errors.append(
627                f"The number of provided arguments ({len(args)}) is greater than "
628                f"the maximum number of supported arguments ({len(self.arg_types)})"
629            )
630
631        return errors
632
633    def dump(self):
634        """
635        Dump this Expression to a JSON-serializable dict.
636        """
637        from sqlglot.serde import dump
638
639        return dump(self)
640
641    @classmethod
642    def load(cls, obj):
643        """
644        Load a dict (as returned by `Expression.dump`) into an Expression instance.
645        """
646        from sqlglot.serde import load
647
648        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
262    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
263        if self.comments is None:
264            self.comments = []
265        if comments:
266            self.comments.extend(comments)
def append(self, arg_key, value):
268    def append(self, arg_key, value):
269        """
270        Appends value to arg_key if it's a list or sets it as a new list.
271
272        Args:
273            arg_key (str): name of the list expression arg
274            value (Any): value to append to the list
275        """
276        if not isinstance(self.args.get(arg_key), list):
277            self.args[arg_key] = []
278        self.args[arg_key].append(value)
279        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
281    def set(self, arg_key, value):
282        """
283        Sets `arg_key` to `value`.
284
285        Args:
286            arg_key (str): name of the expression arg.
287            value: value to set the arg to.
288        """
289        self.args[arg_key] = value
290        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
322    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
335    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
545    def replace(self, expression):
546        """
547        Swap out this expression with a new expression.
548
549        For example::
550
551            >>> tree = Select().select("x").from_("tbl")
552            >>> tree.find(Column).replace(Column(this="y"))
553            (COLUMN this: y)
554            >>> tree.sql()
555            'SELECT y FROM tbl'
556
557        Args:
558            expression (Expression|None): new node
559
560        Returns:
561            The new expression or expressions.
562        """
563        if not self.parent:
564            return expression
565
566        parent = self.parent
567        self.parent = None
568
569        replace_children(parent, lambda child: expression if child is self else child)
570        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
572    def pop(self):
573        """
574        Remove this expression from its AST.
575
576        Returns:
577            The popped expression.
578        """
579        self.replace(None)
580        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
582    def assert_is(self, type_):
583        """
584        Assert that this `Expression` is an instance of `type_`.
585
586        If it is NOT an instance of `type_`, this raises an assertion error.
587        Otherwise, this returns this expression.
588
589        Examples:
590            This is useful for type security in chained expressions:
591
592            >>> import sqlglot
593            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
594            'SELECT x, z FROM y'
595        """
596        assert isinstance(self, type_)
597        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
599    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
600        """
601        Checks if this expression is valid (e.g. all mandatory args are set).
602
603        Args:
604            args: a sequence of values that were used to instantiate a Func expression. This is used
605                to check that the provided arguments don't exceed the function argument limit.
606
607        Returns:
608            A list of error messages for all possible errors that were found.
609        """
610        errors: t.List[str] = []
611
612        for k in self.args:
613            if k not in self.arg_types:
614                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
615        for k, mandatory in self.arg_types.items():
616            v = self.args.get(k)
617            if mandatory and (v is None or (isinstance(v, list) and not v)):
618                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
619
620        if (
621            args
622            and isinstance(self, Func)
623            and len(args) > len(self.arg_types)
624            and not self.is_var_len_args
625        ):
626            errors.append(
627                f"The number of provided arguments ({len(args)}) is greater than "
628                f"the maximum number of supported arguments ({len(self.arg_types)})"
629            )
630
631        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
633    def dump(self):
634        """
635        Dump this Expression to a JSON-serializable dict.
636        """
637        from sqlglot.serde import dump
638
639        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
641    @classmethod
642    def load(cls, obj):
643        """
644        Load a dict (as returned by `Expression.dump`) into an Expression instance.
645        """
646        from sqlglot.serde import load
647
648        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
659class Condition(Expression):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
679
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
699
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)
715
716    def _binop(self, klass: t.Type[E], other: ExpOrStr, reverse=False) -> E:
717        this = self.copy()
718        other = convert(other, copy=True)
719        if not isinstance(this, klass) and not isinstance(other, klass):
720            this = _wrap(this, Binary)
721            other = _wrap(other, Binary)
722        if reverse:
723            return klass(this=other, expression=this)
724        return klass(this=this, expression=other)
725
726    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
727        return Bracket(
728            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
729        )
730
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
739
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
746
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
749
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
752
753    def eq(self, other: ExpOrStr) -> EQ:
754        return self._binop(EQ, other)
755
756    def neq(self, other: ExpOrStr) -> NEQ:
757        return self._binop(NEQ, other)
758
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
761
762    def __lt__(self, other: ExpOrStr) -> LT:
763        return self._binop(LT, other)
764
765    def __le__(self, other: ExpOrStr) -> LTE:
766        return self._binop(LTE, other)
767
768    def __gt__(self, other: ExpOrStr) -> GT:
769        return self._binop(GT, other)
770
771    def __ge__(self, other: ExpOrStr) -> GTE:
772        return self._binop(GTE, other)
773
774    def __add__(self, other: ExpOrStr) -> Add:
775        return self._binop(Add, other)
776
777    def __radd__(self, other: ExpOrStr) -> Add:
778        return self._binop(Add, other, reverse=True)
779
780    def __sub__(self, other: ExpOrStr) -> Sub:
781        return self._binop(Sub, other)
782
783    def __rsub__(self, other: ExpOrStr) -> Sub:
784        return self._binop(Sub, other, reverse=True)
785
786    def __mul__(self, other: ExpOrStr) -> Mul:
787        return self._binop(Mul, other)
788
789    def __rmul__(self, other: ExpOrStr) -> Mul:
790        return self._binop(Mul, other, reverse=True)
791
792    def __truediv__(self, other: ExpOrStr) -> Div:
793        return self._binop(Div, other)
794
795    def __rtruediv__(self, other: ExpOrStr) -> Div:
796        return self._binop(Div, other, reverse=True)
797
798    def __floordiv__(self, other: ExpOrStr) -> IntDiv:
799        return self._binop(IntDiv, other)
800
801    def __rfloordiv__(self, other: ExpOrStr) -> IntDiv:
802        return self._binop(IntDiv, other, reverse=True)
803
804    def __mod__(self, other: ExpOrStr) -> Mod:
805        return self._binop(Mod, other)
806
807    def __rmod__(self, other: ExpOrStr) -> Mod:
808        return self._binop(Mod, other, reverse=True)
809
810    def __pow__(self, other: ExpOrStr) -> Pow:
811        return self._binop(Pow, other)
812
813    def __rpow__(self, other: ExpOrStr) -> Pow:
814        return self._binop(Pow, other, reverse=True)
815
816    def __and__(self, other: ExpOrStr) -> And:
817        return self._binop(And, other)
818
819    def __rand__(self, other: ExpOrStr) -> And:
820        return self._binop(And, other, reverse=True)
821
822    def __or__(self, other: ExpOrStr) -> Or:
823        return self._binop(Or, other)
824
825    def __ror__(self, other: ExpOrStr) -> Or:
826        return self._binop(Or, other, reverse=True)
827
828    def __neg__(self) -> Neg:
829        return Neg(this=_wrap(self.copy(), Binary))
830
831    def __invert__(self) -> Not:
832        return not_(self.copy())
def and_(self, *expressions, dialect=None, copy=True, **opts):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, copy=True, **opts):
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self, copy=True):
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy (bool): whether or not to copy this object.
Returns:

Not: the new condition.

def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
def between( self, low: Any, high: Any, copy=True, **opts) -> sqlglot.expressions.Between:
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
def eq( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.EQ:
753    def eq(self, other: ExpOrStr) -> EQ:
754        return self._binop(EQ, other)
def neq( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.NEQ:
756    def neq(self, other: ExpOrStr) -> NEQ:
757        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
class Predicate(Condition):
835class Predicate(Condition):
836    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
839class DerivedTable(Expression):
840    @property
841    def alias_column_names(self):
842        table_alias = self.args.get("alias")
843        if not table_alias:
844            return []
845        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
846        return [c.name for c in column_list]
847
848    @property
849    def selects(self):
850        return self.this.selects if isinstance(self.this, Subqueryable) else []
851
852    @property
853    def named_selects(self):
854        return [select.output_name for select in self.selects]
class Unionable(Expression):
857class Unionable(Expression):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
877
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
897
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
919class UDTF(DerivedTable, Unionable):
920    @property
921    def selects(self):
922        alias = self.args.get("alias")
923        return alias.columns if alias else []
class Cache(Expression):
926class Cache(Expression):
927    arg_types = {
928        "with": False,
929        "this": True,
930        "lazy": False,
931        "options": False,
932        "expression": False,
933    }
class Uncache(Expression):
936class Uncache(Expression):
937    arg_types = {"this": True, "exists": False}
class Create(Expression):
940class Create(Expression):
941    arg_types = {
942        "with": False,
943        "this": True,
944        "kind": True,
945        "expression": False,
946        "exists": False,
947        "properties": False,
948        "replace": False,
949        "unique": False,
950        "indexes": False,
951        "no_schema_binding": False,
952        "begin": False,
953    }
class Describe(Expression):
956class Describe(Expression):
957    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
960class Pragma(Expression):
961    pass
class Set(Expression):
964class Set(Expression):
965    arg_types = {"expressions": False}
class SetItem(Expression):
968class SetItem(Expression):
969    arg_types = {
970        "this": False,
971        "expressions": False,
972        "kind": False,
973        "collate": False,  # MySQL SET NAMES statement
974        "global": False,
975    }
class Show(Expression):
978class Show(Expression):
979    arg_types = {
980        "this": True,
981        "target": False,
982        "offset": False,
983        "limit": False,
984        "like": False,
985        "where": False,
986        "db": False,
987        "full": False,
988        "mutex": False,
989        "query": False,
990        "channel": False,
991        "global": False,
992        "log": False,
993        "position": False,
994        "types": False,
995    }
class UserDefinedFunction(Expression):
998class UserDefinedFunction(Expression):
999    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1002class CharacterSet(Expression):
1003    arg_types = {"this": True, "default": False}
class With(Expression):
1006class With(Expression):
1007    arg_types = {"expressions": True, "recursive": False}
1008
1009    @property
1010    def recursive(self) -> bool:
1011        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
1014class WithinGroup(Expression):
1015    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1018class CTE(DerivedTable):
1019    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
1022class TableAlias(Expression):
1023    arg_types = {"this": False, "columns": False}
1024
1025    @property
1026    def columns(self):
1027        return self.args.get("columns") or []
class BitString(Condition):
1030class BitString(Condition):
1031    pass
class HexString(Condition):
1034class HexString(Condition):
1035    pass
class ByteString(Condition):
1038class ByteString(Condition):
1039    pass
class Column(Condition):
1042class Column(Condition):
1043    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1044
1045    @property
1046    def table(self) -> str:
1047        return self.text("table")
1048
1049    @property
1050    def db(self) -> str:
1051        return self.text("db")
1052
1053    @property
1054    def catalog(self) -> str:
1055        return self.text("catalog")
1056
1057    @property
1058    def output_name(self) -> str:
1059        return self.name
1060
1061    @property
1062    def parts(self) -> t.List[Identifier]:
1063        """Return the parts of a column in order catalog, db, table, name."""
1064        return [part for part in reversed(list(self.args.values())) if part]
1065
1066    def to_dot(self) -> Dot:
1067        """Converts the column into a dot expression."""
1068        parts = self.parts
1069        parent = self.parent
1070
1071        while parent:
1072            if isinstance(parent, Dot):
1073                parts.append(parent.expression)
1074            parent = parent.parent
1075
1076        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
1066    def to_dot(self) -> Dot:
1067        """Converts the column into a dot expression."""
1068        parts = self.parts
1069        parent = self.parent
1070
1071        while parent:
1072            if isinstance(parent, Dot):
1073                parts.append(parent.expression)
1074            parent = parent.parent
1075
1076        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
1079class ColumnPosition(Expression):
1080    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
1083class ColumnDef(Expression):
1084    arg_types = {
1085        "this": True,
1086        "kind": False,
1087        "constraints": False,
1088        "exists": False,
1089        "position": False,
1090    }
1091
1092    @property
1093    def constraints(self) -> t.List[ColumnConstraint]:
1094        return self.args.get("constraints") or []
class AlterColumn(Expression):
1097class AlterColumn(Expression):
1098    arg_types = {
1099        "this": True,
1100        "dtype": False,
1101        "collate": False,
1102        "using": False,
1103        "default": False,
1104        "drop": False,
1105    }
class RenameTable(Expression):
1108class RenameTable(Expression):
1109    pass
class SetTag(Expression):
1112class SetTag(Expression):
1113    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1116class Comment(Expression):
1117    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
1120class ColumnConstraint(Expression):
1121    arg_types = {"this": False, "kind": True}
1122
1123    @property
1124    def kind(self) -> ColumnConstraintKind:
1125        return self.args["kind"]
class ColumnConstraintKind(Expression):
1128class ColumnConstraintKind(Expression):
1129    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1132class AutoIncrementColumnConstraint(ColumnConstraintKind):
1133    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1136class CaseSpecificColumnConstraint(ColumnConstraintKind):
1137    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1140class CharacterSetColumnConstraint(ColumnConstraintKind):
1141    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1144class CheckColumnConstraint(ColumnConstraintKind):
1145    pass
class CollateColumnConstraint(ColumnConstraintKind):
1148class CollateColumnConstraint(ColumnConstraintKind):
1149    pass
class CommentColumnConstraint(ColumnConstraintKind):
1152class CommentColumnConstraint(ColumnConstraintKind):
1153    pass
class CompressColumnConstraint(ColumnConstraintKind):
1156class CompressColumnConstraint(ColumnConstraintKind):
1157    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1160class DateFormatColumnConstraint(ColumnConstraintKind):
1161    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1164class DefaultColumnConstraint(ColumnConstraintKind):
1165    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1168class EncodeColumnConstraint(ColumnConstraintKind):
1169    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1172class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1173    # this: True -> ALWAYS, this: False -> BY DEFAULT
1174    arg_types = {
1175        "this": False,
1176        "start": False,
1177        "increment": False,
1178        "minvalue": False,
1179        "maxvalue": False,
1180        "cycle": False,
1181    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1184class InlineLengthColumnConstraint(ColumnConstraintKind):
1185    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1188class NotNullColumnConstraint(ColumnConstraintKind):
1189    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1193class OnUpdateColumnConstraint(ColumnConstraintKind):
1194    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1197class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1198    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1201class TitleColumnConstraint(ColumnConstraintKind):
1202    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1205class UniqueColumnConstraint(ColumnConstraintKind):
1206    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1209class UppercaseColumnConstraint(ColumnConstraintKind):
1210    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1213class PathColumnConstraint(ColumnConstraintKind):
1214    pass
class Constraint(Expression):
1217class Constraint(Expression):
1218    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1221class Delete(Expression):
1222    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1223
1224    def delete(
1225        self,
1226        table: ExpOrStr,
1227        dialect: DialectType = None,
1228        copy: bool = True,
1229        **opts,
1230    ) -> Delete:
1231        """
1232        Create a DELETE expression or replace the table on an existing DELETE expression.
1233
1234        Example:
1235            >>> delete("tbl").sql()
1236            'DELETE FROM tbl'
1237
1238        Args:
1239            table: the table from which to delete.
1240            dialect: the dialect used to parse the input expression.
1241            copy: if `False`, modify this expression instance in-place.
1242            opts: other options to use to parse the input expressions.
1243
1244        Returns:
1245            Delete: the modified expression.
1246        """
1247        return _apply_builder(
1248            expression=table,
1249            instance=self,
1250            arg="this",
1251            dialect=dialect,
1252            into=Table,
1253            copy=copy,
1254            **opts,
1255        )
1256
1257    def where(
1258        self,
1259        *expressions: ExpOrStr,
1260        append: bool = True,
1261        dialect: DialectType = None,
1262        copy: bool = True,
1263        **opts,
1264    ) -> Delete:
1265        """
1266        Append to or set the WHERE expressions.
1267
1268        Example:
1269            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1270            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1271
1272        Args:
1273            *expressions: the SQL code strings to parse.
1274                If an `Expression` instance is passed, it will be used as-is.
1275                Multiple expressions are combined with an AND operator.
1276            append: if `True`, AND the new expressions to any existing expression.
1277                Otherwise, this resets the expression.
1278            dialect: the dialect used to parse the input expressions.
1279            copy: if `False`, modify this expression instance in-place.
1280            opts: other options to use to parse the input expressions.
1281
1282        Returns:
1283            Delete: the modified expression.
1284        """
1285        return _apply_conjunction_builder(
1286            *expressions,
1287            instance=self,
1288            arg="where",
1289            append=append,
1290            into=Where,
1291            dialect=dialect,
1292            copy=copy,
1293            **opts,
1294        )
1295
1296    def returning(
1297        self,
1298        expression: ExpOrStr,
1299        dialect: DialectType = None,
1300        copy: bool = True,
1301        **opts,
1302    ) -> Delete:
1303        """
1304        Set the RETURNING expression. Not supported by all dialects.
1305
1306        Example:
1307            >>> delete("tbl").returning("*", dialect="postgres").sql()
1308            'DELETE FROM tbl RETURNING *'
1309
1310        Args:
1311            expression: the SQL code strings to parse.
1312                If an `Expression` instance is passed, it will be used as-is.
1313            dialect: the dialect used to parse the input expressions.
1314            copy: if `False`, modify this expression instance in-place.
1315            opts: other options to use to parse the input expressions.
1316
1317        Returns:
1318            Delete: the modified expression.
1319        """
1320        return _apply_builder(
1321            expression=expression,
1322            instance=self,
1323            arg="returning",
1324            prefix="RETURNING",
1325            dialect=dialect,
1326            copy=copy,
1327            into=Returning,
1328            **opts,
1329        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1224    def delete(
1225        self,
1226        table: ExpOrStr,
1227        dialect: DialectType = None,
1228        copy: bool = True,
1229        **opts,
1230    ) -> Delete:
1231        """
1232        Create a DELETE expression or replace the table on an existing DELETE expression.
1233
1234        Example:
1235            >>> delete("tbl").sql()
1236            'DELETE FROM tbl'
1237
1238        Args:
1239            table: the table from which to delete.
1240            dialect: the dialect used to parse the input expression.
1241            copy: if `False`, modify this expression instance in-place.
1242            opts: other options to use to parse the input expressions.
1243
1244        Returns:
1245            Delete: the modified expression.
1246        """
1247        return _apply_builder(
1248            expression=table,
1249            instance=self,
1250            arg="this",
1251            dialect=dialect,
1252            into=Table,
1253            copy=copy,
1254            **opts,
1255        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1257    def where(
1258        self,
1259        *expressions: ExpOrStr,
1260        append: bool = True,
1261        dialect: DialectType = None,
1262        copy: bool = True,
1263        **opts,
1264    ) -> Delete:
1265        """
1266        Append to or set the WHERE expressions.
1267
1268        Example:
1269            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1270            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1271
1272        Args:
1273            *expressions: the SQL code strings to parse.
1274                If an `Expression` instance is passed, it will be used as-is.
1275                Multiple expressions are combined with an AND operator.
1276            append: if `True`, AND the new expressions to any existing expression.
1277                Otherwise, this resets the expression.
1278            dialect: the dialect used to parse the input expressions.
1279            copy: if `False`, modify this expression instance in-place.
1280            opts: other options to use to parse the input expressions.
1281
1282        Returns:
1283            Delete: the modified expression.
1284        """
1285        return _apply_conjunction_builder(
1286            *expressions,
1287            instance=self,
1288            arg="where",
1289            append=append,
1290            into=Where,
1291            dialect=dialect,
1292            copy=copy,
1293            **opts,
1294        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1296    def returning(
1297        self,
1298        expression: ExpOrStr,
1299        dialect: DialectType = None,
1300        copy: bool = True,
1301        **opts,
1302    ) -> Delete:
1303        """
1304        Set the RETURNING expression. Not supported by all dialects.
1305
1306        Example:
1307            >>> delete("tbl").returning("*", dialect="postgres").sql()
1308            'DELETE FROM tbl RETURNING *'
1309
1310        Args:
1311            expression: the SQL code strings to parse.
1312                If an `Expression` instance is passed, it will be used as-is.
1313            dialect: the dialect used to parse the input expressions.
1314            copy: if `False`, modify this expression instance in-place.
1315            opts: other options to use to parse the input expressions.
1316
1317        Returns:
1318            Delete: the modified expression.
1319        """
1320        return _apply_builder(
1321            expression=expression,
1322            instance=self,
1323            arg="returning",
1324            prefix="RETURNING",
1325            dialect=dialect,
1326            copy=copy,
1327            into=Returning,
1328            **opts,
1329        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1332class Drop(Expression):
1333    arg_types = {
1334        "this": False,
1335        "kind": False,
1336        "exists": False,
1337        "temporary": False,
1338        "materialized": False,
1339        "cascade": False,
1340        "constraints": False,
1341        "purge": False,
1342    }
class Filter(Expression):
1345class Filter(Expression):
1346    arg_types = {"this": True, "expression": True}
class Check(Expression):
1349class Check(Expression):
1350    pass
class Directory(Expression):
1353class Directory(Expression):
1354    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1355    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1358class ForeignKey(Expression):
1359    arg_types = {
1360        "expressions": True,
1361        "reference": False,
1362        "delete": False,
1363        "update": False,
1364    }
class PrimaryKey(Expression):
1367class PrimaryKey(Expression):
1368    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1371class Unique(Expression):
1372    arg_types = {"expressions": True}
class Into(Expression):
1377class Into(Expression):
1378    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1381class From(Expression):
1382    arg_types = {"expressions": True}
class Having(Expression):
1385class Having(Expression):
1386    pass
class Hint(Expression):
1389class Hint(Expression):
1390    arg_types = {"expressions": True}
class JoinHint(Expression):
1393class JoinHint(Expression):
1394    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1397class Identifier(Expression):
1398    arg_types = {"this": True, "quoted": False}
1399
1400    @property
1401    def quoted(self):
1402        return bool(self.args.get("quoted"))
1403
1404    @property
1405    def hashable_args(self) -> t.Any:
1406        if self.quoted and any(char.isupper() for char in self.this):
1407            return (self.this, self.quoted)
1408        return self.this.lower()
1409
1410    @property
1411    def output_name(self):
1412        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1415class Index(Expression):
1416    arg_types = {
1417        "this": False,
1418        "table": False,
1419        "where": False,
1420        "columns": False,
1421        "unique": False,
1422        "primary": False,
1423        "amp": False,  # teradata
1424    }
class Insert(Expression):
1427class Insert(Expression):
1428    arg_types = {
1429        "with": False,
1430        "this": True,
1431        "expression": False,
1432        "conflict": False,
1433        "returning": False,
1434        "overwrite": False,
1435        "exists": False,
1436        "partition": False,
1437        "alternative": False,
1438    }
class OnConflict(Expression):
1441class OnConflict(Expression):
1442    arg_types = {
1443        "duplicate": False,
1444        "expressions": False,
1445        "nothing": False,
1446        "key": False,
1447        "constraint": False,
1448    }
class Returning(Expression):
1451class Returning(Expression):
1452    arg_types = {"expressions": True}
class Introducer(Expression):
1456class Introducer(Expression):
1457    arg_types = {"this": True, "expression": True}
class National(Expression):
1461class National(Expression):
1462    pass
class LoadData(Expression):
1465class LoadData(Expression):
1466    arg_types = {
1467        "this": True,
1468        "local": False,
1469        "overwrite": False,
1470        "inpath": True,
1471        "partition": False,
1472        "input_format": False,
1473        "serde": False,
1474    }
class Partition(Expression):
1477class Partition(Expression):
1478    arg_types = {"expressions": True}
class Fetch(Expression):
1481class Fetch(Expression):
1482    arg_types = {
1483        "direction": False,
1484        "count": False,
1485        "percent": False,
1486        "with_ties": False,
1487    }
class Group(Expression):
1490class Group(Expression):
1491    arg_types = {
1492        "expressions": False,
1493        "grouping_sets": False,
1494        "cube": False,
1495        "rollup": False,
1496    }
class Lambda(Expression):
1499class Lambda(Expression):
1500    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1503class Limit(Expression):
1504    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1507class Literal(Condition):
1508    arg_types = {"this": True, "is_string": True}
1509
1510    @property
1511    def hashable_args(self) -> t.Any:
1512        return (self.this, self.args.get("is_string"))
1513
1514    @classmethod
1515    def number(cls, number) -> Literal:
1516        return cls(this=str(number), is_string=False)
1517
1518    @classmethod
1519    def string(cls, string) -> Literal:
1520        return cls(this=str(string), is_string=True)
1521
1522    @property
1523    def output_name(self):
1524        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1514    @classmethod
1515    def number(cls, number) -> Literal:
1516        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1518    @classmethod
1519    def string(cls, string) -> Literal:
1520        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1527class Join(Expression):
1528    arg_types = {
1529        "this": True,
1530        "on": False,
1531        "side": False,
1532        "kind": False,
1533        "using": False,
1534        "natural": False,
1535        "hint": False,
1536    }
1537
1538    @property
1539    def kind(self):
1540        return self.text("kind").upper()
1541
1542    @property
1543    def side(self):
1544        return self.text("side").upper()
1545
1546    @property
1547    def hint(self):
1548        return self.text("hint").upper()
1549
1550    @property
1551    def alias_or_name(self):
1552        return self.this.alias_or_name
1553
1554    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1555        """
1556        Append to or set the ON expressions.
1557
1558        Example:
1559            >>> import sqlglot
1560            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1561            'JOIN x ON y = 1'
1562
1563        Args:
1564            *expressions (str | Expression): the SQL code strings to parse.
1565                If an `Expression` instance is passed, it will be used as-is.
1566                Multiple expressions are combined with an AND operator.
1567            append (bool): if `True`, AND the new expressions to any existing expression.
1568                Otherwise, this resets the expression.
1569            dialect (str): the dialect used to parse the input expressions.
1570            copy (bool): if `False`, modify this expression instance in-place.
1571            opts (kwargs): other options to use to parse the input expressions.
1572
1573        Returns:
1574            Join: the modified join expression.
1575        """
1576        join = _apply_conjunction_builder(
1577            *expressions,
1578            instance=self,
1579            arg="on",
1580            append=append,
1581            dialect=dialect,
1582            copy=copy,
1583            **opts,
1584        )
1585
1586        if join.kind == "CROSS":
1587            join.set("kind", None)
1588
1589        return join
1590
1591    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1592        """
1593        Append to or set the USING expressions.
1594
1595        Example:
1596            >>> import sqlglot
1597            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1598            'JOIN x USING (foo, bla)'
1599
1600        Args:
1601            *expressions (str | Expression): the SQL code strings to parse.
1602                If an `Expression` instance is passed, it will be used as-is.
1603            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1604                Otherwise, this resets the expression.
1605            dialect (str): the dialect used to parse the input expressions.
1606            copy (bool): if `False`, modify this expression instance in-place.
1607            opts (kwargs): other options to use to parse the input expressions.
1608
1609        Returns:
1610            Join: the modified join expression.
1611        """
1612        join = _apply_list_builder(
1613            *expressions,
1614            instance=self,
1615            arg="using",
1616            append=append,
1617            dialect=dialect,
1618            copy=copy,
1619            **opts,
1620        )
1621
1622        if join.kind == "CROSS":
1623            join.set("kind", None)
1624
1625        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1554    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1555        """
1556        Append to or set the ON expressions.
1557
1558        Example:
1559            >>> import sqlglot
1560            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1561            'JOIN x ON y = 1'
1562
1563        Args:
1564            *expressions (str | Expression): the SQL code strings to parse.
1565                If an `Expression` instance is passed, it will be used as-is.
1566                Multiple expressions are combined with an AND operator.
1567            append (bool): if `True`, AND the new expressions to any existing expression.
1568                Otherwise, this resets the expression.
1569            dialect (str): the dialect used to parse the input expressions.
1570            copy (bool): if `False`, modify this expression instance in-place.
1571            opts (kwargs): other options to use to parse the input expressions.
1572
1573        Returns:
1574            Join: the modified join expression.
1575        """
1576        join = _apply_conjunction_builder(
1577            *expressions,
1578            instance=self,
1579            arg="on",
1580            append=append,
1581            dialect=dialect,
1582            copy=copy,
1583            **opts,
1584        )
1585
1586        if join.kind == "CROSS":
1587            join.set("kind", None)
1588
1589        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1591    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1592        """
1593        Append to or set the USING expressions.
1594
1595        Example:
1596            >>> import sqlglot
1597            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1598            'JOIN x USING (foo, bla)'
1599
1600        Args:
1601            *expressions (str | Expression): the SQL code strings to parse.
1602                If an `Expression` instance is passed, it will be used as-is.
1603            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1604                Otherwise, this resets the expression.
1605            dialect (str): the dialect used to parse the input expressions.
1606            copy (bool): if `False`, modify this expression instance in-place.
1607            opts (kwargs): other options to use to parse the input expressions.
1608
1609        Returns:
1610            Join: the modified join expression.
1611        """
1612        join = _apply_list_builder(
1613            *expressions,
1614            instance=self,
1615            arg="using",
1616            append=append,
1617            dialect=dialect,
1618            copy=copy,
1619            **opts,
1620        )
1621
1622        if join.kind == "CROSS":
1623            join.set("kind", None)
1624
1625        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1628class Lateral(UDTF):
1629    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1632class MatchRecognize(Expression):
1633    arg_types = {
1634        "partition_by": False,
1635        "order": False,
1636        "measures": False,
1637        "rows": False,
1638        "after": False,
1639        "pattern": False,
1640        "define": False,
1641        "alias": False,
1642    }
class Final(Expression):
1647class Final(Expression):
1648    pass
class Offset(Expression):
1651class Offset(Expression):
1652    arg_types = {"this": False, "expression": True}
class Order(Expression):
1655class Order(Expression):
1656    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1661class Cluster(Order):
1662    pass
class Distribute(Order):
1665class Distribute(Order):
1666    pass
class Sort(Order):
1669class Sort(Order):
1670    pass
class Ordered(Expression):
1673class Ordered(Expression):
1674    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1677class Property(Expression):
1678    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1681class AfterJournalProperty(Property):
1682    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1685class AlgorithmProperty(Property):
1686    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1689class AutoIncrementProperty(Property):
1690    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1693class BlockCompressionProperty(Property):
1694    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1697class CharacterSetProperty(Property):
1698    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1701class ChecksumProperty(Property):
1702    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1705class CollateProperty(Property):
1706    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1709class DataBlocksizeProperty(Property):
1710    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1713class DefinerProperty(Property):
1714    arg_types = {"this": True}
class DistKeyProperty(Property):
1717class DistKeyProperty(Property):
1718    arg_types = {"this": True}
class DistStyleProperty(Property):
1721class DistStyleProperty(Property):
1722    arg_types = {"this": True}
class EngineProperty(Property):
1725class EngineProperty(Property):
1726    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1729class ExecuteAsProperty(Property):
1730    arg_types = {"this": True}
class ExternalProperty(Property):
1733class ExternalProperty(Property):
1734    arg_types = {"this": False}
class FallbackProperty(Property):
1737class FallbackProperty(Property):
1738    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1741class FileFormatProperty(Property):
1742    arg_types = {"this": True}
class FreespaceProperty(Property):
1745class FreespaceProperty(Property):
1746    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1749class InputOutputFormat(Expression):
1750    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1753class IsolatedLoadingProperty(Property):
1754    arg_types = {
1755        "no": True,
1756        "concurrent": True,
1757        "for_all": True,
1758        "for_insert": True,
1759        "for_none": True,
1760    }
class JournalProperty(Property):
1763class JournalProperty(Property):
1764    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1767class LanguageProperty(Property):
1768    arg_types = {"this": True}
class LikeProperty(Property):
1771class LikeProperty(Property):
1772    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1775class LocationProperty(Property):
1776    arg_types = {"this": True}
class LockingProperty(Property):
1779class LockingProperty(Property):
1780    arg_types = {
1781        "this": False,
1782        "kind": True,
1783        "for_or_in": True,
1784        "lock_type": True,
1785        "override": False,
1786    }
class LogProperty(Property):
1789class LogProperty(Property):
1790    arg_types = {"no": True}
class MaterializedProperty(Property):
1793class MaterializedProperty(Property):
1794    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1797class MergeBlockRatioProperty(Property):
1798    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1801class NoPrimaryIndexProperty(Property):
1802    arg_types = {"this": False}
class OnCommitProperty(Property):
1805class OnCommitProperty(Property):
1806    arg_type = {"this": False}
class PartitionedByProperty(Property):
1809class PartitionedByProperty(Property):
1810    arg_types = {"this": True}
class ReturnsProperty(Property):
1813class ReturnsProperty(Property):
1814    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1817class RowFormatProperty(Property):
1818    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1821class RowFormatDelimitedProperty(Property):
1822    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1823    arg_types = {
1824        "fields": False,
1825        "escaped": False,
1826        "collection_items": False,
1827        "map_keys": False,
1828        "lines": False,
1829        "null": False,
1830        "serde": False,
1831    }
class RowFormatSerdeProperty(Property):
1834class RowFormatSerdeProperty(Property):
1835    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1838class SchemaCommentProperty(Property):
1839    arg_types = {"this": True}
class SerdeProperties(Property):
1842class SerdeProperties(Property):
1843    arg_types = {"expressions": True}
class SetProperty(Property):
1846class SetProperty(Property):
1847    arg_types = {"multi": True}
class SortKeyProperty(Property):
1850class SortKeyProperty(Property):
1851    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1854class SqlSecurityProperty(Property):
1855    arg_types = {"definer": True}
class StabilityProperty(Property):
1858class StabilityProperty(Property):
1859    arg_types = {"this": True}
class TableFormatProperty(Property):
1862class TableFormatProperty(Property):
1863    arg_types = {"this": True}
class TemporaryProperty(Property):
1866class TemporaryProperty(Property):
1867    arg_types = {"global_": True}
class TransientProperty(Property):
1870class TransientProperty(Property):
1871    arg_types = {"this": False}
class VolatileProperty(Property):
1874class VolatileProperty(Property):
1875    arg_types = {"this": False}
class WithDataProperty(Property):
1878class WithDataProperty(Property):
1879    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1882class WithJournalTableProperty(Property):
1883    arg_types = {"this": True}
class Properties(Expression):
1886class Properties(Expression):
1887    arg_types = {"expressions": True}
1888
1889    NAME_TO_PROPERTY = {
1890        "ALGORITHM": AlgorithmProperty,
1891        "AUTO_INCREMENT": AutoIncrementProperty,
1892        "CHARACTER SET": CharacterSetProperty,
1893        "COLLATE": CollateProperty,
1894        "COMMENT": SchemaCommentProperty,
1895        "DEFINER": DefinerProperty,
1896        "DISTKEY": DistKeyProperty,
1897        "DISTSTYLE": DistStyleProperty,
1898        "ENGINE": EngineProperty,
1899        "EXECUTE AS": ExecuteAsProperty,
1900        "FORMAT": FileFormatProperty,
1901        "LANGUAGE": LanguageProperty,
1902        "LOCATION": LocationProperty,
1903        "PARTITIONED_BY": PartitionedByProperty,
1904        "RETURNS": ReturnsProperty,
1905        "ROW_FORMAT": RowFormatProperty,
1906        "SORTKEY": SortKeyProperty,
1907        "TABLE_FORMAT": TableFormatProperty,
1908    }
1909
1910    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1911
1912    # CREATE property locations
1913    # Form: schema specified
1914    #   create [POST_CREATE]
1915    #     table a [POST_NAME]
1916    #     (b int) [POST_SCHEMA]
1917    #     with ([POST_WITH])
1918    #     index (b) [POST_INDEX]
1919    #
1920    # Form: alias selection
1921    #   create [POST_CREATE]
1922    #     table a [POST_NAME]
1923    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1924    #     index (c) [POST_INDEX]
1925    class Location(AutoName):
1926        POST_CREATE = auto()
1927        POST_NAME = auto()
1928        POST_SCHEMA = auto()
1929        POST_WITH = auto()
1930        POST_ALIAS = auto()
1931        POST_EXPRESSION = auto()
1932        POST_INDEX = auto()
1933        UNSUPPORTED = auto()
1934
1935    @classmethod
1936    def from_dict(cls, properties_dict) -> Properties:
1937        expressions = []
1938        for key, value in properties_dict.items():
1939            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1940            if property_cls:
1941                expressions.append(property_cls(this=convert(value)))
1942            else:
1943                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1944
1945        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1935    @classmethod
1936    def from_dict(cls, properties_dict) -> Properties:
1937        expressions = []
1938        for key, value in properties_dict.items():
1939            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1940            if property_cls:
1941                expressions.append(property_cls(this=convert(value)))
1942            else:
1943                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1944
1945        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1925    class Location(AutoName):
1926        POST_CREATE = auto()
1927        POST_NAME = auto()
1928        POST_SCHEMA = auto()
1929        POST_WITH = auto()
1930        POST_ALIAS = auto()
1931        POST_EXPRESSION = auto()
1932        POST_INDEX = auto()
1933        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1948class Qualify(Expression):
1949    pass
class Return(Expression):
1953class Return(Expression):
1954    pass
class Reference(Expression):
1957class Reference(Expression):
1958    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1961class Tuple(Expression):
1962    arg_types = {"expressions": False}
1963
1964    def isin(
1965        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
1966    ) -> In:
1967        return In(
1968            this=_maybe_copy(self, copy),
1969            expressions=[convert(e, copy=copy) for e in expressions],
1970            query=maybe_parse(query, copy=copy, **opts) if query else None,
1971        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
1964    def isin(
1965        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
1966    ) -> In:
1967        return In(
1968            this=_maybe_copy(self, copy),
1969            expressions=[convert(e, copy=copy) for e in expressions],
1970            query=maybe_parse(query, copy=copy, **opts) if query else None,
1971        )
class Subqueryable(Unionable):
1974class Subqueryable(Unionable):
1975    def subquery(self, alias=None, copy=True) -> Subquery:
1976        """
1977        Convert this expression to an aliased expression that can be used as a Subquery.
1978
1979        Example:
1980            >>> subquery = Select().select("x").from_("tbl").subquery()
1981            >>> Select().select("x").from_(subquery).sql()
1982            'SELECT x FROM (SELECT x FROM tbl)'
1983
1984        Args:
1985            alias (str | Identifier): an optional alias for the subquery
1986            copy (bool): if `False`, modify this expression instance in-place.
1987
1988        Returns:
1989            Alias: the subquery
1990        """
1991        instance = _maybe_copy(self, copy)
1992        return Subquery(
1993            this=instance,
1994            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1995        )
1996
1997    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1998        raise NotImplementedError
1999
2000    @property
2001    def ctes(self):
2002        with_ = self.args.get("with")
2003        if not with_:
2004            return []
2005        return with_.expressions
2006
2007    @property
2008    def selects(self):
2009        raise NotImplementedError("Subqueryable objects must implement `selects`")
2010
2011    @property
2012    def named_selects(self):
2013        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2014
2015    def with_(
2016        self,
2017        alias,
2018        as_,
2019        recursive=None,
2020        append=True,
2021        dialect=None,
2022        copy=True,
2023        **opts,
2024    ):
2025        """
2026        Append to or set the common table expressions.
2027
2028        Example:
2029            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2030            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2031
2032        Args:
2033            alias (str | Expression): the SQL code string to parse as the table name.
2034                If an `Expression` instance is passed, this is used as-is.
2035            as_ (str | Expression): the SQL code string to parse as the table expression.
2036                If an `Expression` instance is passed, it will be used as-is.
2037            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2038            append (bool): if `True`, add to any existing expressions.
2039                Otherwise, this resets the expressions.
2040            dialect (str): the dialect used to parse the input expression.
2041            copy (bool): if `False`, modify this expression instance in-place.
2042            opts (kwargs): other options to use to parse the input expressions.
2043
2044        Returns:
2045            Select: the modified expression.
2046        """
2047        alias_expression = maybe_parse(
2048            alias,
2049            dialect=dialect,
2050            into=TableAlias,
2051            **opts,
2052        )
2053        as_expression = maybe_parse(
2054            as_,
2055            dialect=dialect,
2056            **opts,
2057        )
2058        cte = CTE(
2059            this=as_expression,
2060            alias=alias_expression,
2061        )
2062        return _apply_child_list_builder(
2063            cte,
2064            instance=self,
2065            arg="with",
2066            append=append,
2067            copy=copy,
2068            into=With,
2069            properties={"recursive": recursive or False},
2070        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1975    def subquery(self, alias=None, copy=True) -> Subquery:
1976        """
1977        Convert this expression to an aliased expression that can be used as a Subquery.
1978
1979        Example:
1980            >>> subquery = Select().select("x").from_("tbl").subquery()
1981            >>> Select().select("x").from_(subquery).sql()
1982            'SELECT x FROM (SELECT x FROM tbl)'
1983
1984        Args:
1985            alias (str | Identifier): an optional alias for the subquery
1986            copy (bool): if `False`, modify this expression instance in-place.
1987
1988        Returns:
1989            Alias: the subquery
1990        """
1991        instance = _maybe_copy(self, copy)
1992        return Subquery(
1993            this=instance,
1994            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1995        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1997    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1998        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
2015    def with_(
2016        self,
2017        alias,
2018        as_,
2019        recursive=None,
2020        append=True,
2021        dialect=None,
2022        copy=True,
2023        **opts,
2024    ):
2025        """
2026        Append to or set the common table expressions.
2027
2028        Example:
2029            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2030            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2031
2032        Args:
2033            alias (str | Expression): the SQL code string to parse as the table name.
2034                If an `Expression` instance is passed, this is used as-is.
2035            as_ (str | Expression): the SQL code string to parse as the table expression.
2036                If an `Expression` instance is passed, it will be used as-is.
2037            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2038            append (bool): if `True`, add to any existing expressions.
2039                Otherwise, this resets the expressions.
2040            dialect (str): the dialect used to parse the input expression.
2041            copy (bool): if `False`, modify this expression instance in-place.
2042            opts (kwargs): other options to use to parse the input expressions.
2043
2044        Returns:
2045            Select: the modified expression.
2046        """
2047        alias_expression = maybe_parse(
2048            alias,
2049            dialect=dialect,
2050            into=TableAlias,
2051            **opts,
2052        )
2053        as_expression = maybe_parse(
2054            as_,
2055            dialect=dialect,
2056            **opts,
2057        )
2058        cte = CTE(
2059            this=as_expression,
2060            alias=alias_expression,
2061        )
2062        return _apply_child_list_builder(
2063            cte,
2064            instance=self,
2065            arg="with",
2066            append=append,
2067            copy=copy,
2068            into=With,
2069            properties={"recursive": recursive or False},
2070        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
2094class Table(Expression):
2095    arg_types = {
2096        "this": True,
2097        "alias": False,
2098        "db": False,
2099        "catalog": False,
2100        "laterals": False,
2101        "joins": False,
2102        "pivots": False,
2103        "hints": False,
2104        "system_time": False,
2105    }
2106
2107    @property
2108    def db(self) -> str:
2109        return self.text("db")
2110
2111    @property
2112    def catalog(self) -> str:
2113        return self.text("catalog")
class SystemTime(Expression):
2117class SystemTime(Expression):
2118    arg_types = {
2119        "this": False,
2120        "expression": False,
2121        "kind": True,
2122    }
class Union(Subqueryable):
2125class Union(Subqueryable):
2126    arg_types = {
2127        "with": False,
2128        "this": True,
2129        "expression": True,
2130        "distinct": False,
2131        **QUERY_MODIFIERS,
2132    }
2133
2134    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2135        """
2136        Set the LIMIT expression.
2137
2138        Example:
2139            >>> select("1").union(select("1")).limit(1).sql()
2140            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2141
2142        Args:
2143            expression (str | int | Expression): the SQL code string to parse.
2144                This can also be an integer.
2145                If a `Limit` instance is passed, this is used as-is.
2146                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2147            dialect (str): the dialect used to parse the input expression.
2148            copy (bool): if `False`, modify this expression instance in-place.
2149            opts (kwargs): other options to use to parse the input expressions.
2150
2151        Returns:
2152            Select: The limited subqueryable.
2153        """
2154        return (
2155            select("*")
2156            .from_(self.subquery(alias="_l_0", copy=copy))
2157            .limit(expression, dialect=dialect, copy=False, **opts)
2158        )
2159
2160    def select(
2161        self,
2162        *expressions: ExpOrStr,
2163        append: bool = True,
2164        dialect: DialectType = None,
2165        copy: bool = True,
2166        **opts,
2167    ) -> Union:
2168        """Append to or set the SELECT of the union recursively.
2169
2170        Example:
2171            >>> from sqlglot import parse_one
2172            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2173            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2174
2175        Args:
2176            *expressions: the SQL code strings to parse.
2177                If an `Expression` instance is passed, it will be used as-is.
2178            append: if `True`, add to any existing expressions.
2179                Otherwise, this resets the expressions.
2180            dialect: the dialect used to parse the input expressions.
2181            copy: if `False`, modify this expression instance in-place.
2182            opts: other options to use to parse the input expressions.
2183
2184        Returns:
2185            Union: the modified expression.
2186        """
2187        this = self.copy() if copy else self
2188        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2189        this.expression.unnest().select(
2190            *expressions, append=append, dialect=dialect, copy=False, **opts
2191        )
2192        return this
2193
2194    @property
2195    def named_selects(self):
2196        return self.this.unnest().named_selects
2197
2198    @property
2199    def is_star(self) -> bool:
2200        return self.this.is_star or self.expression.is_star
2201
2202    @property
2203    def selects(self):
2204        return self.this.unnest().selects
2205
2206    @property
2207    def left(self):
2208        return self.this
2209
2210    @property
2211    def right(self):
2212        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2134    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2135        """
2136        Set the LIMIT expression.
2137
2138        Example:
2139            >>> select("1").union(select("1")).limit(1).sql()
2140            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2141
2142        Args:
2143            expression (str | int | Expression): the SQL code string to parse.
2144                This can also be an integer.
2145                If a `Limit` instance is passed, this is used as-is.
2146                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2147            dialect (str): the dialect used to parse the input expression.
2148            copy (bool): if `False`, modify this expression instance in-place.
2149            opts (kwargs): other options to use to parse the input expressions.
2150
2151        Returns:
2152            Select: The limited subqueryable.
2153        """
2154        return (
2155            select("*")
2156            .from_(self.subquery(alias="_l_0", copy=copy))
2157            .limit(expression, dialect=dialect, copy=False, **opts)
2158        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2160    def select(
2161        self,
2162        *expressions: ExpOrStr,
2163        append: bool = True,
2164        dialect: DialectType = None,
2165        copy: bool = True,
2166        **opts,
2167    ) -> Union:
2168        """Append to or set the SELECT of the union recursively.
2169
2170        Example:
2171            >>> from sqlglot import parse_one
2172            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2173            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2174
2175        Args:
2176            *expressions: the SQL code strings to parse.
2177                If an `Expression` instance is passed, it will be used as-is.
2178            append: if `True`, add to any existing expressions.
2179                Otherwise, this resets the expressions.
2180            dialect: the dialect used to parse the input expressions.
2181            copy: if `False`, modify this expression instance in-place.
2182            opts: other options to use to parse the input expressions.
2183
2184        Returns:
2185            Union: the modified expression.
2186        """
2187        this = self.copy() if copy else self
2188        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2189        this.expression.unnest().select(
2190            *expressions, append=append, dialect=dialect, copy=False, **opts
2191        )
2192        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2215class Except(Union):
2216    pass
class Intersect(Union):
2219class Intersect(Union):
2220    pass
class Unnest(UDTF):
2223class Unnest(UDTF):
2224    arg_types = {
2225        "expressions": True,
2226        "ordinality": False,
2227        "alias": False,
2228        "offset": False,
2229    }
class Update(Expression):
2232class Update(Expression):
2233    arg_types = {
2234        "with": False,
2235        "this": False,
2236        "expressions": True,
2237        "from": False,
2238        "where": False,
2239        "returning": False,
2240    }
class Values(UDTF):
2243class Values(UDTF):
2244    arg_types = {
2245        "expressions": True,
2246        "ordinality": False,
2247        "alias": False,
2248    }
class Var(Expression):
2251class Var(Expression):
2252    pass
class Schema(Expression):
2255class Schema(Expression):
2256    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2261class Lock(Expression):
2262    arg_types = {"update": True}
class Select(Subqueryable):
2265class Select(Subqueryable):
2266    arg_types = {
2267        "with": False,
2268        "kind": False,
2269        "expressions": False,
2270        "hint": False,
2271        "distinct": False,
2272        "struct": False,  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table
2273        "value": False,
2274        "into": False,
2275        "from": False,
2276        **QUERY_MODIFIERS,
2277    }
2278
2279    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2280        """
2281        Set the FROM expression.
2282
2283        Example:
2284            >>> Select().from_("tbl").select("x").sql()
2285            'SELECT x FROM tbl'
2286
2287        Args:
2288            *expressions (str | Expression): the SQL code strings to parse.
2289                If a `From` instance is passed, this is used as-is.
2290                If another `Expression` instance is passed, it will be wrapped in a `From`.
2291            append (bool): if `True`, add to any existing expressions.
2292                Otherwise, this flattens all the `From` expression into a single expression.
2293            dialect (str): the dialect used to parse the input expression.
2294            copy (bool): if `False`, modify this expression instance in-place.
2295            opts (kwargs): other options to use to parse the input expressions.
2296
2297        Returns:
2298            Select: the modified expression.
2299        """
2300        return _apply_child_list_builder(
2301            *expressions,
2302            instance=self,
2303            arg="from",
2304            append=append,
2305            copy=copy,
2306            prefix="FROM",
2307            into=From,
2308            dialect=dialect,
2309            **opts,
2310        )
2311
2312    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2313        """
2314        Set the GROUP BY expression.
2315
2316        Example:
2317            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2318            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2319
2320        Args:
2321            *expressions (str | Expression): the SQL code strings to parse.
2322                If a `Group` instance is passed, this is used as-is.
2323                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2324                If nothing is passed in then a group by is not applied to the expression
2325            append (bool): if `True`, add to any existing expressions.
2326                Otherwise, this flattens all the `Group` expression into a single expression.
2327            dialect (str): the dialect used to parse the input expression.
2328            copy (bool): if `False`, modify this expression instance in-place.
2329            opts (kwargs): other options to use to parse the input expressions.
2330
2331        Returns:
2332            Select: the modified expression.
2333        """
2334        if not expressions:
2335            return self if not copy else self.copy()
2336        return _apply_child_list_builder(
2337            *expressions,
2338            instance=self,
2339            arg="group",
2340            append=append,
2341            copy=copy,
2342            prefix="GROUP BY",
2343            into=Group,
2344            dialect=dialect,
2345            **opts,
2346        )
2347
2348    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2349        """
2350        Set the ORDER BY expression.
2351
2352        Example:
2353            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2354            'SELECT x FROM tbl ORDER BY x DESC'
2355
2356        Args:
2357            *expressions (str | Expression): the SQL code strings to parse.
2358                If a `Group` instance is passed, this is used as-is.
2359                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2360            append (bool): if `True`, add to any existing expressions.
2361                Otherwise, this flattens all the `Order` expression into a single expression.
2362            dialect (str): the dialect used to parse the input expression.
2363            copy (bool): if `False`, modify this expression instance in-place.
2364            opts (kwargs): other options to use to parse the input expressions.
2365
2366        Returns:
2367            Select: the modified expression.
2368        """
2369        return _apply_child_list_builder(
2370            *expressions,
2371            instance=self,
2372            arg="order",
2373            append=append,
2374            copy=copy,
2375            prefix="ORDER BY",
2376            into=Order,
2377            dialect=dialect,
2378            **opts,
2379        )
2380
2381    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2382        """
2383        Set the SORT BY expression.
2384
2385        Example:
2386            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2387            'SELECT x FROM tbl SORT BY x DESC'
2388
2389        Args:
2390            *expressions (str | Expression): the SQL code strings to parse.
2391                If a `Group` instance is passed, this is used as-is.
2392                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2393            append (bool): if `True`, add to any existing expressions.
2394                Otherwise, this flattens all the `Order` expression into a single expression.
2395            dialect (str): the dialect used to parse the input expression.
2396            copy (bool): if `False`, modify this expression instance in-place.
2397            opts (kwargs): other options to use to parse the input expressions.
2398
2399        Returns:
2400            Select: the modified expression.
2401        """
2402        return _apply_child_list_builder(
2403            *expressions,
2404            instance=self,
2405            arg="sort",
2406            append=append,
2407            copy=copy,
2408            prefix="SORT BY",
2409            into=Sort,
2410            dialect=dialect,
2411            **opts,
2412        )
2413
2414    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2415        """
2416        Set the CLUSTER BY expression.
2417
2418        Example:
2419            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2420            'SELECT x FROM tbl CLUSTER BY x DESC'
2421
2422        Args:
2423            *expressions (str | Expression): the SQL code strings to parse.
2424                If a `Group` instance is passed, this is used as-is.
2425                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2426            append (bool): if `True`, add to any existing expressions.
2427                Otherwise, this flattens all the `Order` expression into a single expression.
2428            dialect (str): the dialect used to parse the input expression.
2429            copy (bool): if `False`, modify this expression instance in-place.
2430            opts (kwargs): other options to use to parse the input expressions.
2431
2432        Returns:
2433            Select: the modified expression.
2434        """
2435        return _apply_child_list_builder(
2436            *expressions,
2437            instance=self,
2438            arg="cluster",
2439            append=append,
2440            copy=copy,
2441            prefix="CLUSTER BY",
2442            into=Cluster,
2443            dialect=dialect,
2444            **opts,
2445        )
2446
2447    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2448        """
2449        Set the LIMIT expression.
2450
2451        Example:
2452            >>> Select().from_("tbl").select("x").limit(10).sql()
2453            'SELECT x FROM tbl LIMIT 10'
2454
2455        Args:
2456            expression (str | int | Expression): the SQL code string to parse.
2457                This can also be an integer.
2458                If a `Limit` instance is passed, this is used as-is.
2459                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2460            dialect (str): the dialect used to parse the input expression.
2461            copy (bool): if `False`, modify this expression instance in-place.
2462            opts (kwargs): other options to use to parse the input expressions.
2463
2464        Returns:
2465            Select: the modified expression.
2466        """
2467        return _apply_builder(
2468            expression=expression,
2469            instance=self,
2470            arg="limit",
2471            into=Limit,
2472            prefix="LIMIT",
2473            dialect=dialect,
2474            copy=copy,
2475            **opts,
2476        )
2477
2478    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2479        """
2480        Set the OFFSET expression.
2481
2482        Example:
2483            >>> Select().from_("tbl").select("x").offset(10).sql()
2484            'SELECT x FROM tbl OFFSET 10'
2485
2486        Args:
2487            expression (str | int | Expression): the SQL code string to parse.
2488                This can also be an integer.
2489                If a `Offset` instance is passed, this is used as-is.
2490                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2491            dialect (str): the dialect used to parse the input expression.
2492            copy (bool): if `False`, modify this expression instance in-place.
2493            opts (kwargs): other options to use to parse the input expressions.
2494
2495        Returns:
2496            Select: the modified expression.
2497        """
2498        return _apply_builder(
2499            expression=expression,
2500            instance=self,
2501            arg="offset",
2502            into=Offset,
2503            prefix="OFFSET",
2504            dialect=dialect,
2505            copy=copy,
2506            **opts,
2507        )
2508
2509    def select(
2510        self,
2511        *expressions: ExpOrStr,
2512        append: bool = True,
2513        dialect: DialectType = None,
2514        copy: bool = True,
2515        **opts,
2516    ) -> Select:
2517        """
2518        Append to or set the SELECT expressions.
2519
2520        Example:
2521            >>> Select().select("x", "y").sql()
2522            'SELECT x, y'
2523
2524        Args:
2525            *expressions: the SQL code strings to parse.
2526                If an `Expression` instance is passed, it will be used as-is.
2527            append: if `True`, add to any existing expressions.
2528                Otherwise, this resets the expressions.
2529            dialect: the dialect used to parse the input expressions.
2530            copy: if `False`, modify this expression instance in-place.
2531            opts: other options to use to parse the input expressions.
2532
2533        Returns:
2534            Select: the modified expression.
2535        """
2536        return _apply_list_builder(
2537            *expressions,
2538            instance=self,
2539            arg="expressions",
2540            append=append,
2541            dialect=dialect,
2542            copy=copy,
2543            **opts,
2544        )
2545
2546    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2547        """
2548        Append to or set the LATERAL expressions.
2549
2550        Example:
2551            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2552            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2553
2554        Args:
2555            *expressions (str | Expression): the SQL code strings to parse.
2556                If an `Expression` instance is passed, it will be used as-is.
2557            append (bool): if `True`, add to any existing expressions.
2558                Otherwise, this resets the expressions.
2559            dialect (str): the dialect used to parse the input expressions.
2560            copy (bool): if `False`, modify this expression instance in-place.
2561            opts (kwargs): other options to use to parse the input expressions.
2562
2563        Returns:
2564            Select: the modified expression.
2565        """
2566        return _apply_list_builder(
2567            *expressions,
2568            instance=self,
2569            arg="laterals",
2570            append=append,
2571            into=Lateral,
2572            prefix="LATERAL VIEW",
2573            dialect=dialect,
2574            copy=copy,
2575            **opts,
2576        )
2577
2578    def join(
2579        self,
2580        expression,
2581        on=None,
2582        using=None,
2583        append=True,
2584        join_type=None,
2585        join_alias=None,
2586        dialect=None,
2587        copy=True,
2588        **opts,
2589    ) -> Select:
2590        """
2591        Append to or set the JOIN expressions.
2592
2593        Example:
2594            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2595            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2596
2597            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2598            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2599
2600            Use `join_type` to change the type of join:
2601
2602            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2603            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2604
2605        Args:
2606            expression (str | Expression): the SQL code string to parse.
2607                If an `Expression` instance is passed, it will be used as-is.
2608            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2609                If an `Expression` instance is passed, it will be used as-is.
2610            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2611                If an `Expression` instance is passed, it will be used as-is.
2612            append (bool): if `True`, add to any existing expressions.
2613                Otherwise, this resets the expressions.
2614            join_type (str): If set, alter the parsed join type
2615            dialect (str): the dialect used to parse the input expressions.
2616            copy (bool): if `False`, modify this expression instance in-place.
2617            opts (kwargs): other options to use to parse the input expressions.
2618
2619        Returns:
2620            Select: the modified expression.
2621        """
2622        parse_args = {"dialect": dialect, **opts}
2623
2624        try:
2625            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2626        except ParseError:
2627            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2628
2629        join = expression if isinstance(expression, Join) else Join(this=expression)
2630
2631        if isinstance(join.this, Select):
2632            join.this.replace(join.this.subquery())
2633
2634        if join_type:
2635            natural: t.Optional[Token]
2636            side: t.Optional[Token]
2637            kind: t.Optional[Token]
2638
2639            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2640
2641            if natural:
2642                join.set("natural", True)
2643            if side:
2644                join.set("side", side.text)
2645            if kind:
2646                join.set("kind", kind.text)
2647
2648        if on:
2649            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2650            join.set("on", on)
2651
2652        if using:
2653            join = _apply_list_builder(
2654                *ensure_collection(using),
2655                instance=join,
2656                arg="using",
2657                append=append,
2658                copy=copy,
2659                **opts,
2660            )
2661
2662        if join_alias:
2663            join.set("this", alias_(join.this, join_alias, table=True))
2664        return _apply_list_builder(
2665            join,
2666            instance=self,
2667            arg="joins",
2668            append=append,
2669            copy=copy,
2670            **opts,
2671        )
2672
2673    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2674        """
2675        Append to or set the WHERE expressions.
2676
2677        Example:
2678            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2679            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2680
2681        Args:
2682            *expressions (str | Expression): the SQL code strings to parse.
2683                If an `Expression` instance is passed, it will be used as-is.
2684                Multiple expressions are combined with an AND operator.
2685            append (bool): if `True`, AND the new expressions to any existing expression.
2686                Otherwise, this resets the expression.
2687            dialect (str): the dialect used to parse the input expressions.
2688            copy (bool): if `False`, modify this expression instance in-place.
2689            opts (kwargs): other options to use to parse the input expressions.
2690
2691        Returns:
2692            Select: the modified expression.
2693        """
2694        return _apply_conjunction_builder(
2695            *expressions,
2696            instance=self,
2697            arg="where",
2698            append=append,
2699            into=Where,
2700            dialect=dialect,
2701            copy=copy,
2702            **opts,
2703        )
2704
2705    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2706        """
2707        Append to or set the HAVING expressions.
2708
2709        Example:
2710            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2711            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2712
2713        Args:
2714            *expressions (str | Expression): the SQL code strings to parse.
2715                If an `Expression` instance is passed, it will be used as-is.
2716                Multiple expressions are combined with an AND operator.
2717            append (bool): if `True`, AND the new expressions to any existing expression.
2718                Otherwise, this resets the expression.
2719            dialect (str): the dialect used to parse the input expressions.
2720            copy (bool): if `False`, modify this expression instance in-place.
2721            opts (kwargs): other options to use to parse the input expressions.
2722
2723        Returns:
2724            Select: the modified expression.
2725        """
2726        return _apply_conjunction_builder(
2727            *expressions,
2728            instance=self,
2729            arg="having",
2730            append=append,
2731            into=Having,
2732            dialect=dialect,
2733            copy=copy,
2734            **opts,
2735        )
2736
2737    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2738        return _apply_list_builder(
2739            *expressions,
2740            instance=self,
2741            arg="windows",
2742            append=append,
2743            into=Window,
2744            dialect=dialect,
2745            copy=copy,
2746            **opts,
2747        )
2748
2749    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2750        return _apply_conjunction_builder(
2751            *expressions,
2752            instance=self,
2753            arg="qualify",
2754            append=append,
2755            into=Qualify,
2756            dialect=dialect,
2757            copy=copy,
2758            **opts,
2759        )
2760
2761    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2762        """
2763        Set the OFFSET expression.
2764
2765        Example:
2766            >>> Select().from_("tbl").select("x").distinct().sql()
2767            'SELECT DISTINCT x FROM tbl'
2768
2769        Args:
2770            ons: the expressions to distinct on
2771            distinct: whether the Select should be distinct
2772            copy: if `False`, modify this expression instance in-place.
2773
2774        Returns:
2775            Select: the modified expression.
2776        """
2777        instance = _maybe_copy(self, copy)
2778        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2779        instance.set("distinct", Distinct(on=on) if distinct else None)
2780        return instance
2781
2782    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2783        """
2784        Convert this expression to a CREATE TABLE AS statement.
2785
2786        Example:
2787            >>> Select().select("*").from_("tbl").ctas("x").sql()
2788            'CREATE TABLE x AS SELECT * FROM tbl'
2789
2790        Args:
2791            table (str | Expression): the SQL code string to parse as the table name.
2792                If another `Expression` instance is passed, it will be used as-is.
2793            properties (dict): an optional mapping of table properties
2794            dialect (str): the dialect used to parse the input table.
2795            copy (bool): if `False`, modify this expression instance in-place.
2796            opts (kwargs): other options to use to parse the input table.
2797
2798        Returns:
2799            Create: the CREATE TABLE AS expression
2800        """
2801        instance = _maybe_copy(self, copy)
2802        table_expression = maybe_parse(
2803            table,
2804            into=Table,
2805            dialect=dialect,
2806            **opts,
2807        )
2808        properties_expression = None
2809        if properties:
2810            properties_expression = Properties.from_dict(properties)
2811
2812        return Create(
2813            this=table_expression,
2814            kind="table",
2815            expression=instance,
2816            properties=properties_expression,
2817        )
2818
2819    def lock(self, update: bool = True, copy: bool = True) -> Select:
2820        """
2821        Set the locking read mode for this expression.
2822
2823        Examples:
2824            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2825            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2826
2827            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2828            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2829
2830        Args:
2831            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2832            copy: if `False`, modify this expression instance in-place.
2833
2834        Returns:
2835            The modified expression.
2836        """
2837
2838        inst = _maybe_copy(self, copy)
2839        inst.set("lock", Lock(update=update))
2840
2841        return inst
2842
2843    @property
2844    def named_selects(self) -> t.List[str]:
2845        return [e.output_name for e in self.expressions if e.alias_or_name]
2846
2847    @property
2848    def is_star(self) -> bool:
2849        return any(expression.is_star for expression in self.expressions)
2850
2851    @property
2852    def selects(self) -> t.List[Expression]:
2853        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2279    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2280        """
2281        Set the FROM expression.
2282
2283        Example:
2284            >>> Select().from_("tbl").select("x").sql()
2285            'SELECT x FROM tbl'
2286
2287        Args:
2288            *expressions (str | Expression): the SQL code strings to parse.
2289                If a `From` instance is passed, this is used as-is.
2290                If another `Expression` instance is passed, it will be wrapped in a `From`.
2291            append (bool): if `True`, add to any existing expressions.
2292                Otherwise, this flattens all the `From` expression into a single expression.
2293            dialect (str): the dialect used to parse the input expression.
2294            copy (bool): if `False`, modify this expression instance in-place.
2295            opts (kwargs): other options to use to parse the input expressions.
2296
2297        Returns:
2298            Select: the modified expression.
2299        """
2300        return _apply_child_list_builder(
2301            *expressions,
2302            instance=self,
2303            arg="from",
2304            append=append,
2305            copy=copy,
2306            prefix="FROM",
2307            into=From,
2308            dialect=dialect,
2309            **opts,
2310        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2312    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2313        """
2314        Set the GROUP BY expression.
2315
2316        Example:
2317            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2318            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2319
2320        Args:
2321            *expressions (str | Expression): the SQL code strings to parse.
2322                If a `Group` instance is passed, this is used as-is.
2323                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2324                If nothing is passed in then a group by is not applied to the expression
2325            append (bool): if `True`, add to any existing expressions.
2326                Otherwise, this flattens all the `Group` expression into a single expression.
2327            dialect (str): the dialect used to parse the input expression.
2328            copy (bool): if `False`, modify this expression instance in-place.
2329            opts (kwargs): other options to use to parse the input expressions.
2330
2331        Returns:
2332            Select: the modified expression.
2333        """
2334        if not expressions:
2335            return self if not copy else self.copy()
2336        return _apply_child_list_builder(
2337            *expressions,
2338            instance=self,
2339            arg="group",
2340            append=append,
2341            copy=copy,
2342            prefix="GROUP BY",
2343            into=Group,
2344            dialect=dialect,
2345            **opts,
2346        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2348    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2349        """
2350        Set the ORDER BY expression.
2351
2352        Example:
2353            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2354            'SELECT x FROM tbl ORDER BY x DESC'
2355
2356        Args:
2357            *expressions (str | Expression): the SQL code strings to parse.
2358                If a `Group` instance is passed, this is used as-is.
2359                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2360            append (bool): if `True`, add to any existing expressions.
2361                Otherwise, this flattens all the `Order` expression into a single expression.
2362            dialect (str): the dialect used to parse the input expression.
2363            copy (bool): if `False`, modify this expression instance in-place.
2364            opts (kwargs): other options to use to parse the input expressions.
2365
2366        Returns:
2367            Select: the modified expression.
2368        """
2369        return _apply_child_list_builder(
2370            *expressions,
2371            instance=self,
2372            arg="order",
2373            append=append,
2374            copy=copy,
2375            prefix="ORDER BY",
2376            into=Order,
2377            dialect=dialect,
2378            **opts,
2379        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2381    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2382        """
2383        Set the SORT BY expression.
2384
2385        Example:
2386            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2387            'SELECT x FROM tbl SORT BY x DESC'
2388
2389        Args:
2390            *expressions (str | Expression): the SQL code strings to parse.
2391                If a `Group` instance is passed, this is used as-is.
2392                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2393            append (bool): if `True`, add to any existing expressions.
2394                Otherwise, this flattens all the `Order` expression into a single expression.
2395            dialect (str): the dialect used to parse the input expression.
2396            copy (bool): if `False`, modify this expression instance in-place.
2397            opts (kwargs): other options to use to parse the input expressions.
2398
2399        Returns:
2400            Select: the modified expression.
2401        """
2402        return _apply_child_list_builder(
2403            *expressions,
2404            instance=self,
2405            arg="sort",
2406            append=append,
2407            copy=copy,
2408            prefix="SORT BY",
2409            into=Sort,
2410            dialect=dialect,
2411            **opts,
2412        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2414    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2415        """
2416        Set the CLUSTER BY expression.
2417
2418        Example:
2419            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2420            'SELECT x FROM tbl CLUSTER BY x DESC'
2421
2422        Args:
2423            *expressions (str | Expression): the SQL code strings to parse.
2424                If a `Group` instance is passed, this is used as-is.
2425                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2426            append (bool): if `True`, add to any existing expressions.
2427                Otherwise, this flattens all the `Order` expression into a single expression.
2428            dialect (str): the dialect used to parse the input expression.
2429            copy (bool): if `False`, modify this expression instance in-place.
2430            opts (kwargs): other options to use to parse the input expressions.
2431
2432        Returns:
2433            Select: the modified expression.
2434        """
2435        return _apply_child_list_builder(
2436            *expressions,
2437            instance=self,
2438            arg="cluster",
2439            append=append,
2440            copy=copy,
2441            prefix="CLUSTER BY",
2442            into=Cluster,
2443            dialect=dialect,
2444            **opts,
2445        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2447    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2448        """
2449        Set the LIMIT expression.
2450
2451        Example:
2452            >>> Select().from_("tbl").select("x").limit(10).sql()
2453            'SELECT x FROM tbl LIMIT 10'
2454
2455        Args:
2456            expression (str | int | Expression): the SQL code string to parse.
2457                This can also be an integer.
2458                If a `Limit` instance is passed, this is used as-is.
2459                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2460            dialect (str): the dialect used to parse the input expression.
2461            copy (bool): if `False`, modify this expression instance in-place.
2462            opts (kwargs): other options to use to parse the input expressions.
2463
2464        Returns:
2465            Select: the modified expression.
2466        """
2467        return _apply_builder(
2468            expression=expression,
2469            instance=self,
2470            arg="limit",
2471            into=Limit,
2472            prefix="LIMIT",
2473            dialect=dialect,
2474            copy=copy,
2475            **opts,
2476        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2478    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2479        """
2480        Set the OFFSET expression.
2481
2482        Example:
2483            >>> Select().from_("tbl").select("x").offset(10).sql()
2484            'SELECT x FROM tbl OFFSET 10'
2485
2486        Args:
2487            expression (str | int | Expression): the SQL code string to parse.
2488                This can also be an integer.
2489                If a `Offset` instance is passed, this is used as-is.
2490                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2491            dialect (str): the dialect used to parse the input expression.
2492            copy (bool): if `False`, modify this expression instance in-place.
2493            opts (kwargs): other options to use to parse the input expressions.
2494
2495        Returns:
2496            Select: the modified expression.
2497        """
2498        return _apply_builder(
2499            expression=expression,
2500            instance=self,
2501            arg="offset",
2502            into=Offset,
2503            prefix="OFFSET",
2504            dialect=dialect,
2505            copy=copy,
2506            **opts,
2507        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2509    def select(
2510        self,
2511        *expressions: ExpOrStr,
2512        append: bool = True,
2513        dialect: DialectType = None,
2514        copy: bool = True,
2515        **opts,
2516    ) -> Select:
2517        """
2518        Append to or set the SELECT expressions.
2519
2520        Example:
2521            >>> Select().select("x", "y").sql()
2522            'SELECT x, y'
2523
2524        Args:
2525            *expressions: the SQL code strings to parse.
2526                If an `Expression` instance is passed, it will be used as-is.
2527            append: if `True`, add to any existing expressions.
2528                Otherwise, this resets the expressions.
2529            dialect: the dialect used to parse the input expressions.
2530            copy: if `False`, modify this expression instance in-place.
2531            opts: other options to use to parse the input expressions.
2532
2533        Returns:
2534            Select: the modified expression.
2535        """
2536        return _apply_list_builder(
2537            *expressions,
2538            instance=self,
2539            arg="expressions",
2540            append=append,
2541            dialect=dialect,
2542            copy=copy,
2543            **opts,
2544        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2546    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2547        """
2548        Append to or set the LATERAL expressions.
2549
2550        Example:
2551            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2552            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2553
2554        Args:
2555            *expressions (str | Expression): the SQL code strings to parse.
2556                If an `Expression` instance is passed, it will be used as-is.
2557            append (bool): if `True`, add to any existing expressions.
2558                Otherwise, this resets the expressions.
2559            dialect (str): the dialect used to parse the input expressions.
2560            copy (bool): if `False`, modify this expression instance in-place.
2561            opts (kwargs): other options to use to parse the input expressions.
2562
2563        Returns:
2564            Select: the modified expression.
2565        """
2566        return _apply_list_builder(
2567            *expressions,
2568            instance=self,
2569            arg="laterals",
2570            append=append,
2571            into=Lateral,
2572            prefix="LATERAL VIEW",
2573            dialect=dialect,
2574            copy=copy,
2575            **opts,
2576        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2578    def join(
2579        self,
2580        expression,
2581        on=None,
2582        using=None,
2583        append=True,
2584        join_type=None,
2585        join_alias=None,
2586        dialect=None,
2587        copy=True,
2588        **opts,
2589    ) -> Select:
2590        """
2591        Append to or set the JOIN expressions.
2592
2593        Example:
2594            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2595            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2596
2597            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2598            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2599
2600            Use `join_type` to change the type of join:
2601
2602            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2603            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2604
2605        Args:
2606            expression (str | Expression): the SQL code string to parse.
2607                If an `Expression` instance is passed, it will be used as-is.
2608            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2609                If an `Expression` instance is passed, it will be used as-is.
2610            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2611                If an `Expression` instance is passed, it will be used as-is.
2612            append (bool): if `True`, add to any existing expressions.
2613                Otherwise, this resets the expressions.
2614            join_type (str): If set, alter the parsed join type
2615            dialect (str): the dialect used to parse the input expressions.
2616            copy (bool): if `False`, modify this expression instance in-place.
2617            opts (kwargs): other options to use to parse the input expressions.
2618
2619        Returns:
2620            Select: the modified expression.
2621        """
2622        parse_args = {"dialect": dialect, **opts}
2623
2624        try:
2625            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2626        except ParseError:
2627            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2628
2629        join = expression if isinstance(expression, Join) else Join(this=expression)
2630
2631        if isinstance(join.this, Select):
2632            join.this.replace(join.this.subquery())
2633
2634        if join_type:
2635            natural: t.Optional[Token]
2636            side: t.Optional[Token]
2637            kind: t.Optional[Token]
2638
2639            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2640
2641            if natural:
2642                join.set("natural", True)
2643            if side:
2644                join.set("side", side.text)
2645            if kind:
2646                join.set("kind", kind.text)
2647
2648        if on:
2649            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2650            join.set("on", on)
2651
2652        if using:
2653            join = _apply_list_builder(
2654                *ensure_collection(using),
2655                instance=join,
2656                arg="using",
2657                append=append,
2658                copy=copy,
2659                **opts,
2660            )
2661
2662        if join_alias:
2663            join.set("this", alias_(join.this, join_alias, table=True))
2664        return _apply_list_builder(
2665            join,
2666            instance=self,
2667            arg="joins",
2668            append=append,
2669            copy=copy,
2670            **opts,
2671        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2673    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2674        """
2675        Append to or set the WHERE expressions.
2676
2677        Example:
2678            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2679            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2680
2681        Args:
2682            *expressions (str | Expression): the SQL code strings to parse.
2683                If an `Expression` instance is passed, it will be used as-is.
2684                Multiple expressions are combined with an AND operator.
2685            append (bool): if `True`, AND the new expressions to any existing expression.
2686                Otherwise, this resets the expression.
2687            dialect (str): the dialect used to parse the input expressions.
2688            copy (bool): if `False`, modify this expression instance in-place.
2689            opts (kwargs): other options to use to parse the input expressions.
2690
2691        Returns:
2692            Select: the modified expression.
2693        """
2694        return _apply_conjunction_builder(
2695            *expressions,
2696            instance=self,
2697            arg="where",
2698            append=append,
2699            into=Where,
2700            dialect=dialect,
2701            copy=copy,
2702            **opts,
2703        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2705    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2706        """
2707        Append to or set the HAVING expressions.
2708
2709        Example:
2710            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2711            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2712
2713        Args:
2714            *expressions (str | Expression): the SQL code strings to parse.
2715                If an `Expression` instance is passed, it will be used as-is.
2716                Multiple expressions are combined with an AND operator.
2717            append (bool): if `True`, AND the new expressions to any existing expression.
2718                Otherwise, this resets the expression.
2719            dialect (str): the dialect used to parse the input expressions.
2720            copy (bool): if `False`, modify this expression instance in-place.
2721            opts (kwargs): other options to use to parse the input expressions.
2722
2723        Returns:
2724            Select: the modified expression.
2725        """
2726        return _apply_conjunction_builder(
2727            *expressions,
2728            instance=self,
2729            arg="having",
2730            append=append,
2731            into=Having,
2732            dialect=dialect,
2733            copy=copy,
2734            **opts,
2735        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2737    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2738        return _apply_list_builder(
2739            *expressions,
2740            instance=self,
2741            arg="windows",
2742            append=append,
2743            into=Window,
2744            dialect=dialect,
2745            copy=copy,
2746            **opts,
2747        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2749    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2750        return _apply_conjunction_builder(
2751            *expressions,
2752            instance=self,
2753            arg="qualify",
2754            append=append,
2755            into=Qualify,
2756            dialect=dialect,
2757            copy=copy,
2758            **opts,
2759        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2761    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2762        """
2763        Set the OFFSET expression.
2764
2765        Example:
2766            >>> Select().from_("tbl").select("x").distinct().sql()
2767            'SELECT DISTINCT x FROM tbl'
2768
2769        Args:
2770            ons: the expressions to distinct on
2771            distinct: whether the Select should be distinct
2772            copy: if `False`, modify this expression instance in-place.
2773
2774        Returns:
2775            Select: the modified expression.
2776        """
2777        instance = _maybe_copy(self, copy)
2778        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2779        instance.set("distinct", Distinct(on=on) if distinct else None)
2780        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2782    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2783        """
2784        Convert this expression to a CREATE TABLE AS statement.
2785
2786        Example:
2787            >>> Select().select("*").from_("tbl").ctas("x").sql()
2788            'CREATE TABLE x AS SELECT * FROM tbl'
2789
2790        Args:
2791            table (str | Expression): the SQL code string to parse as the table name.
2792                If another `Expression` instance is passed, it will be used as-is.
2793            properties (dict): an optional mapping of table properties
2794            dialect (str): the dialect used to parse the input table.
2795            copy (bool): if `False`, modify this expression instance in-place.
2796            opts (kwargs): other options to use to parse the input table.
2797
2798        Returns:
2799            Create: the CREATE TABLE AS expression
2800        """
2801        instance = _maybe_copy(self, copy)
2802        table_expression = maybe_parse(
2803            table,
2804            into=Table,
2805            dialect=dialect,
2806            **opts,
2807        )
2808        properties_expression = None
2809        if properties:
2810            properties_expression = Properties.from_dict(properties)
2811
2812        return Create(
2813            this=table_expression,
2814            kind="table",
2815            expression=instance,
2816            properties=properties_expression,
2817        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2819    def lock(self, update: bool = True, copy: bool = True) -> Select:
2820        """
2821        Set the locking read mode for this expression.
2822
2823        Examples:
2824            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2825            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2826
2827            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2828            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2829
2830        Args:
2831            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2832            copy: if `False`, modify this expression instance in-place.
2833
2834        Returns:
2835            The modified expression.
2836        """
2837
2838        inst = _maybe_copy(self, copy)
2839        inst.set("lock", Lock(update=update))
2840
2841        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2856class Subquery(DerivedTable, Unionable):
2857    arg_types = {
2858        "this": True,
2859        "alias": False,
2860        "with": False,
2861        **QUERY_MODIFIERS,
2862    }
2863
2864    def unnest(self):
2865        """
2866        Returns the first non subquery.
2867        """
2868        expression = self
2869        while isinstance(expression, Subquery):
2870            expression = expression.this
2871        return expression
2872
2873    @property
2874    def is_star(self) -> bool:
2875        return self.this.is_star
2876
2877    @property
2878    def output_name(self):
2879        return self.alias
def unnest(self):
2864    def unnest(self):
2865        """
2866        Returns the first non subquery.
2867        """
2868        expression = self
2869        while isinstance(expression, Subquery):
2870            expression = expression.this
2871        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2882class TableSample(Expression):
2883    arg_types = {
2884        "this": False,
2885        "method": False,
2886        "bucket_numerator": False,
2887        "bucket_denominator": False,
2888        "bucket_field": False,
2889        "percent": False,
2890        "rows": False,
2891        "size": False,
2892        "seed": False,
2893        "kind": False,
2894    }
class Tag(Expression):
2897class Tag(Expression):
2898    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2899
2900    arg_types = {
2901        "this": False,
2902        "prefix": False,
2903        "postfix": False,
2904    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2907class Pivot(Expression):
2908    arg_types = {
2909        "this": False,
2910        "alias": False,
2911        "expressions": True,
2912        "field": True,
2913        "unpivot": True,
2914        "columns": False,
2915    }
class Window(Expression):
2918class Window(Expression):
2919    arg_types = {
2920        "this": True,
2921        "partition_by": False,
2922        "order": False,
2923        "spec": False,
2924        "alias": False,
2925        "over": False,
2926        "first": False,
2927    }
class WindowSpec(Expression):
2930class WindowSpec(Expression):
2931    arg_types = {
2932        "kind": False,
2933        "start": False,
2934        "start_side": False,
2935        "end": False,
2936        "end_side": False,
2937    }
class Where(Expression):
2940class Where(Expression):
2941    pass
class Star(Expression):
2944class Star(Expression):
2945    arg_types = {"except": False, "replace": False}
2946
2947    @property
2948    def name(self) -> str:
2949        return "*"
2950
2951    @property
2952    def output_name(self):
2953        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2956class Parameter(Expression):
2957    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2960class SessionParameter(Expression):
2961    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2964class Placeholder(Expression):
2965    arg_types = {"this": False}
class Null(Condition):
2968class Null(Condition):
2969    arg_types: t.Dict[str, t.Any] = {}
2970
2971    @property
2972    def name(self) -> str:
2973        return "NULL"
class Boolean(Condition):
2976class Boolean(Condition):
2977    pass
class DataType(Expression):
2980class DataType(Expression):
2981    arg_types = {
2982        "this": True,
2983        "expressions": False,
2984        "nested": False,
2985        "values": False,
2986        "prefix": False,
2987    }
2988
2989    class Type(AutoName):
2990        CHAR = auto()
2991        NCHAR = auto()
2992        VARCHAR = auto()
2993        NVARCHAR = auto()
2994        TEXT = auto()
2995        MEDIUMTEXT = auto()
2996        LONGTEXT = auto()
2997        MEDIUMBLOB = auto()
2998        LONGBLOB = auto()
2999        BINARY = auto()
3000        VARBINARY = auto()
3001        INT = auto()
3002        UINT = auto()
3003        TINYINT = auto()
3004        UTINYINT = auto()
3005        SMALLINT = auto()
3006        USMALLINT = auto()
3007        BIGINT = auto()
3008        UBIGINT = auto()
3009        INT128 = auto()
3010        UINT128 = auto()
3011        INT256 = auto()
3012        UINT256 = auto()
3013        FLOAT = auto()
3014        DOUBLE = auto()
3015        DECIMAL = auto()
3016        BIGDECIMAL = auto()
3017        BIT = auto()
3018        BOOLEAN = auto()
3019        JSON = auto()
3020        JSONB = auto()
3021        INTERVAL = auto()
3022        TIME = auto()
3023        TIMESTAMP = auto()
3024        TIMESTAMPTZ = auto()
3025        TIMESTAMPLTZ = auto()
3026        DATE = auto()
3027        DATETIME = auto()
3028        ARRAY = auto()
3029        MAP = auto()
3030        UUID = auto()
3031        GEOGRAPHY = auto()
3032        GEOMETRY = auto()
3033        STRUCT = auto()
3034        NULLABLE = auto()
3035        HLLSKETCH = auto()
3036        HSTORE = auto()
3037        SUPER = auto()
3038        SERIAL = auto()
3039        SMALLSERIAL = auto()
3040        BIGSERIAL = auto()
3041        XML = auto()
3042        UNIQUEIDENTIFIER = auto()
3043        MONEY = auto()
3044        SMALLMONEY = auto()
3045        ROWVERSION = auto()
3046        IMAGE = auto()
3047        VARIANT = auto()
3048        OBJECT = auto()
3049        INET = auto()
3050        NULL = auto()
3051        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3052
3053    TEXT_TYPES = {
3054        Type.CHAR,
3055        Type.NCHAR,
3056        Type.VARCHAR,
3057        Type.NVARCHAR,
3058        Type.TEXT,
3059    }
3060
3061    INTEGER_TYPES = {
3062        Type.INT,
3063        Type.TINYINT,
3064        Type.SMALLINT,
3065        Type.BIGINT,
3066        Type.INT128,
3067        Type.INT256,
3068    }
3069
3070    FLOAT_TYPES = {
3071        Type.FLOAT,
3072        Type.DOUBLE,
3073    }
3074
3075    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3076
3077    TEMPORAL_TYPES = {
3078        Type.TIMESTAMP,
3079        Type.TIMESTAMPTZ,
3080        Type.TIMESTAMPLTZ,
3081        Type.DATE,
3082        Type.DATETIME,
3083    }
3084
3085    @classmethod
3086    def build(
3087        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3088    ) -> DataType:
3089        from sqlglot import parse_one
3090
3091        if isinstance(dtype, str):
3092            if dtype.upper() in cls.Type.__members__:
3093                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3094            else:
3095                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3096            if data_type_exp is None:
3097                raise ValueError(f"Unparsable data type value: {dtype}")
3098        elif isinstance(dtype, DataType.Type):
3099            data_type_exp = DataType(this=dtype)
3100        elif isinstance(dtype, DataType):
3101            return dtype
3102        else:
3103            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3104        return DataType(**{**data_type_exp.args, **kwargs})
3105
3106    def is_type(self, dtype: DataType.Type) -> bool:
3107        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3085    @classmethod
3086    def build(
3087        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3088    ) -> DataType:
3089        from sqlglot import parse_one
3090
3091        if isinstance(dtype, str):
3092            if dtype.upper() in cls.Type.__members__:
3093                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3094            else:
3095                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3096            if data_type_exp is None:
3097                raise ValueError(f"Unparsable data type value: {dtype}")
3098        elif isinstance(dtype, DataType.Type):
3099            data_type_exp = DataType(this=dtype)
3100        elif isinstance(dtype, DataType):
3101            return dtype
3102        else:
3103            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3104        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3106    def is_type(self, dtype: DataType.Type) -> bool:
3107        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2989    class Type(AutoName):
2990        CHAR = auto()
2991        NCHAR = auto()
2992        VARCHAR = auto()
2993        NVARCHAR = auto()
2994        TEXT = auto()
2995        MEDIUMTEXT = auto()
2996        LONGTEXT = auto()
2997        MEDIUMBLOB = auto()
2998        LONGBLOB = auto()
2999        BINARY = auto()
3000        VARBINARY = auto()
3001        INT = auto()
3002        UINT = auto()
3003        TINYINT = auto()
3004        UTINYINT = auto()
3005        SMALLINT = auto()
3006        USMALLINT = auto()
3007        BIGINT = auto()
3008        UBIGINT = auto()
3009        INT128 = auto()
3010        UINT128 = auto()
3011        INT256 = auto()
3012        UINT256 = auto()
3013        FLOAT = auto()
3014        DOUBLE = auto()
3015        DECIMAL = auto()
3016        BIGDECIMAL = auto()
3017        BIT = auto()
3018        BOOLEAN = auto()
3019        JSON = auto()
3020        JSONB = auto()
3021        INTERVAL = auto()
3022        TIME = auto()
3023        TIMESTAMP = auto()
3024        TIMESTAMPTZ = auto()
3025        TIMESTAMPLTZ = auto()
3026        DATE = auto()
3027        DATETIME = auto()
3028        ARRAY = auto()
3029        MAP = auto()
3030        UUID = auto()
3031        GEOGRAPHY = auto()
3032        GEOMETRY = auto()
3033        STRUCT = auto()
3034        NULLABLE = auto()
3035        HLLSKETCH = auto()
3036        HSTORE = auto()
3037        SUPER = auto()
3038        SERIAL = auto()
3039        SMALLSERIAL = auto()
3040        BIGSERIAL = auto()
3041        XML = auto()
3042        UNIQUEIDENTIFIER = auto()
3043        MONEY = auto()
3044        SMALLMONEY = auto()
3045        ROWVERSION = auto()
3046        IMAGE = auto()
3047        VARIANT = auto()
3048        OBJECT = auto()
3049        INET = auto()
3050        NULL = auto()
3051        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
INT128 = <Type.INT128: 'INT128'>
UINT128 = <Type.UINT128: 'UINT128'>
INT256 = <Type.INT256: 'INT256'>
UINT256 = <Type.UINT256: 'UINT256'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3111class PseudoType(Expression):
3112    pass
class SubqueryPredicate(Predicate):
3116class SubqueryPredicate(Predicate):
3117    pass
class All(SubqueryPredicate):
3120class All(SubqueryPredicate):
3121    pass
class Any(SubqueryPredicate):
3124class Any(SubqueryPredicate):
3125    pass
class Exists(SubqueryPredicate):
3128class Exists(SubqueryPredicate):
3129    pass
class Command(Expression):
3134class Command(Expression):
3135    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3138class Transaction(Expression):
3139    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3142class Commit(Expression):
3143    arg_types = {"chain": False}
class Rollback(Expression):
3146class Rollback(Expression):
3147    arg_types = {"savepoint": False}
class AlterTable(Expression):
3150class AlterTable(Expression):
3151    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3154class AddConstraint(Expression):
3155    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3158class DropPartition(Expression):
3159    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3163class Binary(Condition):
3164    arg_types = {"this": True, "expression": True}
3165
3166    @property
3167    def left(self):
3168        return self.this
3169
3170    @property
3171    def right(self):
3172        return self.expression
class Add(Binary):
3175class Add(Binary):
3176    pass
class Connector(Binary):
3179class Connector(Binary):
3180    pass
class And(Connector):
3183class And(Connector):
3184    pass
class Or(Connector):
3187class Or(Connector):
3188    pass
class BitwiseAnd(Binary):
3191class BitwiseAnd(Binary):
3192    pass
class BitwiseLeftShift(Binary):
3195class BitwiseLeftShift(Binary):
3196    pass
class BitwiseOr(Binary):
3199class BitwiseOr(Binary):
3200    pass
class BitwiseRightShift(Binary):
3203class BitwiseRightShift(Binary):
3204    pass
class BitwiseXor(Binary):
3207class BitwiseXor(Binary):
3208    pass
class Div(Binary):
3211class Div(Binary):
3212    pass
class Overlaps(Binary):
3215class Overlaps(Binary):
3216    pass
class Dot(Binary):
3219class Dot(Binary):
3220    @property
3221    def name(self) -> str:
3222        return self.expression.name
3223
3224    @classmethod
3225    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3226        """Build a Dot object with a sequence of expressions."""
3227        if len(expressions) < 2:
3228            raise ValueError(f"Dot requires >= 2 expressions.")
3229
3230        a, b, *expressions = expressions
3231        dot = Dot(this=a, expression=b)
3232
3233        for expression in expressions:
3234            dot = Dot(this=dot, expression=expression)
3235
3236        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3224    @classmethod
3225    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3226        """Build a Dot object with a sequence of expressions."""
3227        if len(expressions) < 2:
3228            raise ValueError(f"Dot requires >= 2 expressions.")
3229
3230        a, b, *expressions = expressions
3231        dot = Dot(this=a, expression=b)
3232
3233        for expression in expressions:
3234            dot = Dot(this=dot, expression=expression)
3235
3236        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3239class DPipe(Binary):
3240    pass
class EQ(Binary, Predicate):
3243class EQ(Binary, Predicate):
3244    pass
class NullSafeEQ(Binary, Predicate):
3247class NullSafeEQ(Binary, Predicate):
3248    pass
class NullSafeNEQ(Binary, Predicate):
3251class NullSafeNEQ(Binary, Predicate):
3252    pass
class Distance(Binary):
3255class Distance(Binary):
3256    pass
class Escape(Binary):
3259class Escape(Binary):
3260    pass
class Glob(Binary, Predicate):
3263class Glob(Binary, Predicate):
3264    pass
class GT(Binary, Predicate):
3267class GT(Binary, Predicate):
3268    pass
class GTE(Binary, Predicate):
3271class GTE(Binary, Predicate):
3272    pass
class ILike(Binary, Predicate):
3275class ILike(Binary, Predicate):
3276    pass
class ILikeAny(Binary, Predicate):
3279class ILikeAny(Binary, Predicate):
3280    pass
class IntDiv(Binary):
3283class IntDiv(Binary):
3284    pass
class Is(Binary, Predicate):
3287class Is(Binary, Predicate):
3288    pass
class Kwarg(Binary):
3291class Kwarg(Binary):
3292    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3295class Like(Binary, Predicate):
3296    pass
class LikeAny(Binary, Predicate):
3299class LikeAny(Binary, Predicate):
3300    pass
class LT(Binary, Predicate):
3303class LT(Binary, Predicate):
3304    pass
class LTE(Binary, Predicate):
3307class LTE(Binary, Predicate):
3308    pass
class Mod(Binary):
3311class Mod(Binary):
3312    pass
class Mul(Binary):
3315class Mul(Binary):
3316    pass
class NEQ(Binary, Predicate):
3319class NEQ(Binary, Predicate):
3320    pass
class SimilarTo(Binary, Predicate):
3323class SimilarTo(Binary, Predicate):
3324    pass
class Slice(Binary):
3327class Slice(Binary):
3328    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3331class Sub(Binary):
3332    pass
class ArrayOverlaps(Binary):
3335class ArrayOverlaps(Binary):
3336    pass
class Unary(Condition):
3341class Unary(Condition):
3342    pass
class BitwiseNot(Unary):
3345class BitwiseNot(Unary):
3346    pass
class Not(Unary):
3349class Not(Unary):
3350    pass
class Paren(Unary):
3353class Paren(Unary):
3354    arg_types = {"this": True, "with": False}
class Neg(Unary):
3357class Neg(Unary):
3358    pass
class Alias(Expression):
3361class Alias(Expression):
3362    arg_types = {"this": True, "alias": False}
3363
3364    @property
3365    def output_name(self):
3366        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3369class Aliases(Expression):
3370    arg_types = {"this": True, "expressions": True}
3371
3372    @property
3373    def aliases(self):
3374        return self.expressions
class AtTimeZone(Expression):
3377class AtTimeZone(Expression):
3378    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3381class Between(Predicate):
3382    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3385class Bracket(Condition):
3386    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3389class Distinct(Expression):
3390    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3393class In(Predicate):
3394    arg_types = {
3395        "this": True,
3396        "expressions": False,
3397        "query": False,
3398        "unnest": False,
3399        "field": False,
3400        "is_global": False,
3401    }
class TimeUnit(Expression):
3404class TimeUnit(Expression):
3405    """Automatically converts unit arg into a var."""
3406
3407    arg_types = {"unit": False}
3408
3409    def __init__(self, **args):
3410        unit = args.get("unit")
3411        if isinstance(unit, (Column, Literal)):
3412            args["unit"] = Var(this=unit.name)
3413        elif isinstance(unit, Week):
3414            unit.set("this", Var(this=unit.this.name))
3415        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3409    def __init__(self, **args):
3410        unit = args.get("unit")
3411        if isinstance(unit, (Column, Literal)):
3412            args["unit"] = Var(this=unit.name)
3413        elif isinstance(unit, Week):
3414            unit.set("this", Var(this=unit.this.name))
3415        super().__init__(**args)
class Interval(TimeUnit):
3418class Interval(TimeUnit):
3419    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3422class IgnoreNulls(Expression):
3423    pass
class RespectNulls(Expression):
3426class RespectNulls(Expression):
3427    pass
class Func(Condition):
3431class Func(Condition):
3432    """
3433    The base class for all function expressions.
3434
3435    Attributes:
3436        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3437            treated as a variable length argument and the argument's value will be stored as a list.
3438        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3439            for this function expression. These values are used to map this node to a name during parsing
3440            as well as to provide the function's name during SQL string generation. By default the SQL
3441            name is set to the expression's class name transformed to snake case.
3442    """
3443
3444    is_var_len_args = False
3445
3446    @classmethod
3447    def from_arg_list(cls, args):
3448        if cls.is_var_len_args:
3449            all_arg_keys = list(cls.arg_types)
3450            # If this function supports variable length argument treat the last argument as such.
3451            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3452            num_non_var = len(non_var_len_arg_keys)
3453
3454            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3455            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3456        else:
3457            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3458
3459        return cls(**args_dict)
3460
3461    @classmethod
3462    def sql_names(cls):
3463        if cls is Func:
3464            raise NotImplementedError(
3465                "SQL name is only supported by concrete function implementations"
3466            )
3467        if "_sql_names" not in cls.__dict__:
3468            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3469        return cls._sql_names
3470
3471    @classmethod
3472    def sql_name(cls):
3473        return cls.sql_names()[0]
3474
3475    @classmethod
3476    def default_parser_mappings(cls):
3477        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3446    @classmethod
3447    def from_arg_list(cls, args):
3448        if cls.is_var_len_args:
3449            all_arg_keys = list(cls.arg_types)
3450            # If this function supports variable length argument treat the last argument as such.
3451            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3452            num_non_var = len(non_var_len_arg_keys)
3453
3454            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3455            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3456        else:
3457            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3458
3459        return cls(**args_dict)
@classmethod
def sql_names(cls):
3461    @classmethod
3462    def sql_names(cls):
3463        if cls is Func:
3464            raise NotImplementedError(
3465                "SQL name is only supported by concrete function implementations"
3466            )
3467        if "_sql_names" not in cls.__dict__:
3468            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3469        return cls._sql_names
@classmethod
def sql_name(cls):
3471    @classmethod
3472    def sql_name(cls):
3473        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3475    @classmethod
3476    def default_parser_mappings(cls):
3477        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3480class AggFunc(Func):
3481    pass
class Abs(Func):
3484class Abs(Func):
3485    pass
class Anonymous(Func):
3488class Anonymous(Func):
3489    arg_types = {"this": True, "expressions": False}
3490    is_var_len_args = True
class Hll(AggFunc):
3495class Hll(AggFunc):
3496    arg_types = {"this": True, "expressions": False}
3497    is_var_len_args = True
class ApproxDistinct(AggFunc):
3500class ApproxDistinct(AggFunc):
3501    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3504class Array(Func):
3505    arg_types = {"expressions": False}
3506    is_var_len_args = True
class ToChar(Func):
3510class ToChar(Func):
3511    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3514class GenerateSeries(Func):
3515    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3518class ArrayAgg(AggFunc):
3519    pass
class ArrayAll(Func):
3522class ArrayAll(Func):
3523    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3526class ArrayAny(Func):
3527    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3530class ArrayConcat(Func):
3531    arg_types = {"this": True, "expressions": False}
3532    is_var_len_args = True
class ArrayContains(Binary, Func):
3535class ArrayContains(Binary, Func):
3536    pass
class ArrayContained(Binary):
3539class ArrayContained(Binary):
3540    pass
class ArrayFilter(Func):
3543class ArrayFilter(Func):
3544    arg_types = {"this": True, "expression": True}
3545    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3548class ArrayJoin(Func):
3549    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3552class ArraySize(Func):
3553    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3556class ArraySort(Func):
3557    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3560class ArraySum(Func):
3561    pass
class ArrayUnionAgg(AggFunc):
3564class ArrayUnionAgg(AggFunc):
3565    pass
class Avg(AggFunc):
3568class Avg(AggFunc):
3569    pass
class AnyValue(AggFunc):
3572class AnyValue(AggFunc):
3573    pass
class Case(Func):
3576class Case(Func):
3577    arg_types = {"this": False, "ifs": True, "default": False}
3578
3579    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3580        instance = _maybe_copy(self, copy)
3581        instance.append(
3582            "ifs",
3583            If(
3584                this=maybe_parse(condition, copy=copy, **opts),
3585                true=maybe_parse(then, copy=copy, **opts),
3586            ),
3587        )
3588        return instance
3589
3590    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3591        instance = _maybe_copy(self, copy)
3592        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3593        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3579    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3580        instance = _maybe_copy(self, copy)
3581        instance.append(
3582            "ifs",
3583            If(
3584                this=maybe_parse(condition, copy=copy, **opts),
3585                true=maybe_parse(then, copy=copy, **opts),
3586            ),
3587        )
3588        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3590    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3591        instance = _maybe_copy(self, copy)
3592        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3593        return instance
class Cast(Func):
3596class Cast(Func):
3597    arg_types = {"this": True, "to": True}
3598
3599    @property
3600    def name(self) -> str:
3601        return self.this.name
3602
3603    @property
3604    def to(self):
3605        return self.args["to"]
3606
3607    @property
3608    def output_name(self):
3609        return self.name
3610
3611    def is_type(self, dtype: DataType.Type) -> bool:
3612        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3611    def is_type(self, dtype: DataType.Type) -> bool:
3612        return self.to.is_type(dtype)
class Collate(Binary):
3615class Collate(Binary):
3616    pass
class TryCast(Cast):
3619class TryCast(Cast):
3620    pass
class Ceil(Func):
3623class Ceil(Func):
3624    arg_types = {"this": True, "decimals": False}
3625    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3628class Coalesce(Func):
3629    arg_types = {"this": True, "expressions": False}
3630    is_var_len_args = True
class Concat(Func):
3633class Concat(Func):
3634    arg_types = {"expressions": True}
3635    is_var_len_args = True
class ConcatWs(Concat):
3638class ConcatWs(Concat):
3639    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3642class Count(AggFunc):
3643    arg_types = {"this": False}
class CountIf(AggFunc):
3646class CountIf(AggFunc):
3647    pass
class CurrentDate(Func):
3650class CurrentDate(Func):
3651    arg_types = {"this": False}
class CurrentDatetime(Func):
3654class CurrentDatetime(Func):
3655    arg_types = {"this": False}
class CurrentTime(Func):
3658class CurrentTime(Func):
3659    arg_types = {"this": False}
class CurrentTimestamp(Func):
3662class CurrentTimestamp(Func):
3663    arg_types = {"this": False}
class CurrentUser(Func):
3666class CurrentUser(Func):
3667    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3670class DateAdd(Func, TimeUnit):
3671    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3674class DateSub(Func, TimeUnit):
3675    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3678class DateDiff(Func, TimeUnit):
3679    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3680    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3683class DateTrunc(Func):
3684    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3687class DatetimeAdd(Func, TimeUnit):
3688    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3691class DatetimeSub(Func, TimeUnit):
3692    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3695class DatetimeDiff(Func, TimeUnit):
3696    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3699class DatetimeTrunc(Func, TimeUnit):
3700    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3703class DayOfWeek(Func):
3704    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3707class DayOfMonth(Func):
3708    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3711class DayOfYear(Func):
3712    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3715class WeekOfYear(Func):
3716    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3719class LastDateOfMonth(Func):
3720    pass
class Extract(Func):
3723class Extract(Func):
3724    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3727class TimestampAdd(Func, TimeUnit):
3728    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3731class TimestampSub(Func, TimeUnit):
3732    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3735class TimestampDiff(Func, TimeUnit):
3736    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3739class TimestampTrunc(Func, TimeUnit):
3740    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3743class TimeAdd(Func, TimeUnit):
3744    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3747class TimeSub(Func, TimeUnit):
3748    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3751class TimeDiff(Func, TimeUnit):
3752    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3755class TimeTrunc(Func, TimeUnit):
3756    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3759class DateFromParts(Func):
3760    _sql_names = ["DATEFROMPARTS"]
3761    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3764class DateStrToDate(Func):
3765    pass
class DateToDateStr(Func):
3768class DateToDateStr(Func):
3769    pass
class DateToDi(Func):
3772class DateToDi(Func):
3773    pass
class Day(Func):
3776class Day(Func):
3777    pass
class Decode(Func):
3780class Decode(Func):
3781    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3784class DiToDate(Func):
3785    pass
class Encode(Func):
3788class Encode(Func):
3789    arg_types = {"this": True, "charset": True}
class Exp(Func):
3792class Exp(Func):
3793    pass
class Explode(Func):
3796class Explode(Func):
3797    pass
class ExponentialTimeDecayedAvg(AggFunc):
3800class ExponentialTimeDecayedAvg(AggFunc):
3801    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3804class Floor(Func):
3805    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
3808class FromBase64(Func):
3809    pass
class ToBase64(Func):
3812class ToBase64(Func):
3813    pass
class Greatest(Func):
3816class Greatest(Func):
3817    arg_types = {"this": True, "expressions": False}
3818    is_var_len_args = True
class GroupConcat(Func):
3821class GroupConcat(Func):
3822    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3825class GroupUniqArray(AggFunc):
3826    arg_types = {"this": True, "size": False}
class Hex(Func):
3829class Hex(Func):
3830    pass
class Histogram(AggFunc):
3833class Histogram(AggFunc):
3834    arg_types = {"this": True, "bins": False}
class If(Func):
3837class If(Func):
3838    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3841class IfNull(Func):
3842    arg_types = {"this": True, "expression": False}
3843    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3846class Initcap(Func):
3847    pass
class JSONKeyValue(Expression):
3850class JSONKeyValue(Expression):
3851    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3854class JSONObject(Func):
3855    arg_types = {
3856        "expressions": False,
3857        "null_handling": False,
3858        "unique_keys": False,
3859        "return_type": False,
3860        "format_json": False,
3861        "encoding": False,
3862    }
class JSONBContains(Binary):
3865class JSONBContains(Binary):
3866    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3869class JSONExtract(Binary, Func):
3870    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3873class JSONExtractScalar(JSONExtract):
3874    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3877class JSONBExtract(JSONExtract):
3878    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3881class JSONBExtractScalar(JSONExtract):
3882    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3885class JSONFormat(Func):
3886    arg_types = {"this": False, "options": False}
3887    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3890class Least(Func):
3891    arg_types = {"expressions": False}
3892    is_var_len_args = True
class Length(Func):
3895class Length(Func):
3896    pass
class Levenshtein(Func):
3899class Levenshtein(Func):
3900    arg_types = {
3901        "this": True,
3902        "expression": False,
3903        "ins_cost": False,
3904        "del_cost": False,
3905        "sub_cost": False,
3906    }
class Ln(Func):
3909class Ln(Func):
3910    pass
class Log(Func):
3913class Log(Func):
3914    arg_types = {"this": True, "expression": False}
class Log2(Func):
3917class Log2(Func):
3918    pass
class Log10(Func):
3921class Log10(Func):
3922    pass
class LogicalOr(AggFunc):
3925class LogicalOr(AggFunc):
3926    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3929class LogicalAnd(AggFunc):
3930    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3933class Lower(Func):
3934    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3937class Map(Func):
3938    arg_types = {"keys": False, "values": False}
class StarMap(Func):
3941class StarMap(Func):
3942    pass
class VarMap(Func):
3945class VarMap(Func):
3946    arg_types = {"keys": True, "values": True}
3947    is_var_len_args = True
class MatchAgainst(Func):
3951class MatchAgainst(Func):
3952    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
3955class Max(AggFunc):
3956    arg_types = {"this": True, "expressions": False}
3957    is_var_len_args = True
class MD5(Func):
3960class MD5(Func):
3961    _sql_names = ["MD5"]
class Min(AggFunc):
3964class Min(AggFunc):
3965    arg_types = {"this": True, "expressions": False}
3966    is_var_len_args = True
class Month(Func):
3969class Month(Func):
3970    pass
class Nvl2(Func):
3973class Nvl2(Func):
3974    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3977class Posexplode(Func):
3978    pass
class Pow(Binary, Func):
3981class Pow(Binary, Func):
3982    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3985class PercentileCont(AggFunc):
3986    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
3989class PercentileDisc(AggFunc):
3990    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
3993class Quantile(AggFunc):
3994    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3999class Quantiles(AggFunc):
4000    arg_types = {"parameters": True, "expressions": True}
4001    is_var_len_args = True
class QuantileIf(AggFunc):
4004class QuantileIf(AggFunc):
4005    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
4008class ApproxQuantile(Quantile):
4009    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4012class RangeN(Func):
4013    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4016class ReadCSV(Func):
4017    _sql_names = ["READ_CSV"]
4018    is_var_len_args = True
4019    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4022class Reduce(Func):
4023    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4026class RegexpExtract(Func):
4027    arg_types = {
4028        "this": True,
4029        "expression": True,
4030        "position": False,
4031        "occurrence": False,
4032        "group": False,
4033    }
class RegexpLike(Func):
4036class RegexpLike(Func):
4037    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4040class RegexpILike(Func):
4041    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4046class RegexpSplit(Func):
4047    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4050class Repeat(Func):
4051    arg_types = {"this": True, "times": True}
class Round(Func):
4054class Round(Func):
4055    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4058class RowNumber(Func):
4059    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4062class SafeDivide(Func):
4063    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4066class SetAgg(AggFunc):
4067    pass
class SHA(Func):
4070class SHA(Func):
4071    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4074class SHA2(Func):
4075    _sql_names = ["SHA2"]
4076    arg_types = {"this": True, "length": False}
class SortArray(Func):
4079class SortArray(Func):
4080    arg_types = {"this": True, "asc": False}
class Split(Func):
4083class Split(Func):
4084    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4089class Substring(Func):
4090    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
4093class StrPosition(Func):
4094    arg_types = {
4095        "this": True,
4096        "substr": True,
4097        "position": False,
4098        "instance": False,
4099    }
class StrToDate(Func):
4102class StrToDate(Func):
4103    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4106class StrToTime(Func):
4107    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4112class StrToUnix(Func):
4113    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4116class NumberToStr(Func):
4117    arg_types = {"this": True, "format": True}
class Struct(Func):
4120class Struct(Func):
4121    arg_types = {"expressions": True}
4122    is_var_len_args = True
class StructExtract(Func):
4125class StructExtract(Func):
4126    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4129class Sum(AggFunc):
4130    pass
class Sqrt(Func):
4133class Sqrt(Func):
4134    pass
class Stddev(AggFunc):
4137class Stddev(AggFunc):
4138    pass
class StddevPop(AggFunc):
4141class StddevPop(AggFunc):
4142    pass
class StddevSamp(AggFunc):
4145class StddevSamp(AggFunc):
4146    pass
class TimeToStr(Func):
4149class TimeToStr(Func):
4150    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4153class TimeToTimeStr(Func):
4154    pass
class TimeToUnix(Func):
4157class TimeToUnix(Func):
4158    pass
class TimeStrToDate(Func):
4161class TimeStrToDate(Func):
4162    pass
class TimeStrToTime(Func):
4165class TimeStrToTime(Func):
4166    pass
class TimeStrToUnix(Func):
4169class TimeStrToUnix(Func):
4170    pass
class Trim(Func):
4173class Trim(Func):
4174    arg_types = {
4175        "this": True,
4176        "expression": False,
4177        "position": False,
4178        "collation": False,
4179    }
class TsOrDsAdd(Func, TimeUnit):
4182class TsOrDsAdd(Func, TimeUnit):
4183    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4186class TsOrDsToDateStr(Func):
4187    pass
class TsOrDsToDate(Func):
4190class TsOrDsToDate(Func):
4191    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4194class TsOrDiToDi(Func):
4195    pass
class Unhex(Func):
4198class Unhex(Func):
4199    pass
class UnixToStr(Func):
4202class UnixToStr(Func):
4203    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4208class UnixToTime(Func):
4209    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4210
4211    SECONDS = Literal.string("seconds")
4212    MILLIS = Literal.string("millis")
4213    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4216class UnixToTimeStr(Func):
4217    pass
class Upper(Func):
4220class Upper(Func):
4221    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4224class Variance(AggFunc):
4225    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4228class VariancePop(AggFunc):
4229    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4232class Week(Func):
4233    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4236class XMLTable(Func):
4237    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4240class Year(Func):
4241    pass
class Use(Expression):
4244class Use(Expression):
4245    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4248class Merge(Expression):
4249    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4252class When(Func):
4253    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4258class NextValueFor(Func):
4259    arg_types = {"this": True, "order": False}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4296def maybe_parse(
4297    sql_or_expression: ExpOrStr,
4298    *,
4299    into: t.Optional[IntoType] = None,
4300    dialect: DialectType = None,
4301    prefix: t.Optional[str] = None,
4302    copy: bool = False,
4303    **opts,
4304) -> Expression:
4305    """Gracefully handle a possible string or expression.
4306
4307    Example:
4308        >>> maybe_parse("1")
4309        (LITERAL this: 1, is_string: False)
4310        >>> maybe_parse(to_identifier("x"))
4311        (IDENTIFIER this: x, quoted: False)
4312
4313    Args:
4314        sql_or_expression: the SQL code string or an expression
4315        into: the SQLGlot Expression to parse into
4316        dialect: the dialect used to parse the input expressions (in the case that an
4317            input expression is a SQL string).
4318        prefix: a string to prefix the sql with before it gets parsed
4319            (automatically includes a space)
4320        copy: whether or not to copy the expression.
4321        **opts: other options to use to parse the input expressions (again, in the case
4322            that an input expression is a SQL string).
4323
4324    Returns:
4325        Expression: the parsed or given expression.
4326    """
4327    if isinstance(sql_or_expression, Expression):
4328        if copy:
4329            return sql_or_expression.copy()
4330        return sql_or_expression
4331
4332    import sqlglot
4333
4334    sql = str(sql_or_expression)
4335    if prefix:
4336        sql = f"{prefix} {sql}"
4337    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4485def union(left, right, distinct=True, dialect=None, **opts):
4486    """
4487    Initializes a syntax tree from one UNION expression.
4488
4489    Example:
4490        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4491        'SELECT * FROM foo UNION SELECT * FROM bla'
4492
4493    Args:
4494        left (str | Expression): the SQL code string corresponding to the left-hand side.
4495            If an `Expression` instance is passed, it will be used as-is.
4496        right (str | Expression): the SQL code string corresponding to the right-hand side.
4497            If an `Expression` instance is passed, it will be used as-is.
4498        distinct (bool): set the DISTINCT flag if and only if this is true.
4499        dialect (str): the dialect used to parse the input expression.
4500        opts (kwargs): other options to use to parse the input expressions.
4501    Returns:
4502        Union: the syntax tree for the UNION expression.
4503    """
4504    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4505    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4506
4507    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4510def intersect(left, right, distinct=True, dialect=None, **opts):
4511    """
4512    Initializes a syntax tree from one INTERSECT expression.
4513
4514    Example:
4515        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4516        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4517
4518    Args:
4519        left (str | Expression): the SQL code string corresponding to the left-hand side.
4520            If an `Expression` instance is passed, it will be used as-is.
4521        right (str | Expression): the SQL code string corresponding to the right-hand side.
4522            If an `Expression` instance is passed, it will be used as-is.
4523        distinct (bool): set the DISTINCT flag if and only if this is true.
4524        dialect (str): the dialect used to parse the input expression.
4525        opts (kwargs): other options to use to parse the input expressions.
4526    Returns:
4527        Intersect: the syntax tree for the INTERSECT expression.
4528    """
4529    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4530    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4531
4532    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4535def except_(left, right, distinct=True, dialect=None, **opts):
4536    """
4537    Initializes a syntax tree from one EXCEPT expression.
4538
4539    Example:
4540        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4541        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4542
4543    Args:
4544        left (str | Expression): the SQL code string corresponding to the left-hand side.
4545            If an `Expression` instance is passed, it will be used as-is.
4546        right (str | Expression): the SQL code string corresponding to the right-hand side.
4547            If an `Expression` instance is passed, it will be used as-is.
4548        distinct (bool): set the DISTINCT flag if and only if this is true.
4549        dialect (str): the dialect used to parse the input expression.
4550        opts (kwargs): other options to use to parse the input expressions.
4551    Returns:
4552        Except: the syntax tree for the EXCEPT statement.
4553    """
4554    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4555    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4556
4557    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4560def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4561    """
4562    Initializes a syntax tree from one or multiple SELECT expressions.
4563
4564    Example:
4565        >>> select("col1", "col2").from_("tbl").sql()
4566        'SELECT col1, col2 FROM tbl'
4567
4568    Args:
4569        *expressions: the SQL code string to parse as the expressions of a
4570            SELECT statement. If an Expression instance is passed, this is used as-is.
4571        dialect: the dialect used to parse the input expressions (in the case that an
4572            input expression is a SQL string).
4573        **opts: other options to use to parse the input expressions (again, in the case
4574            that an input expression is a SQL string).
4575
4576    Returns:
4577        Select: the syntax tree for the SELECT statement.
4578    """
4579    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4582def from_(*expressions, dialect=None, **opts) -> Select:
4583    """
4584    Initializes a syntax tree from a FROM expression.
4585
4586    Example:
4587        >>> from_("tbl").select("col1", "col2").sql()
4588        'SELECT col1, col2 FROM tbl'
4589
4590    Args:
4591        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4592            SELECT statement. If an Expression instance is passed, this is used as-is.
4593        dialect (str): the dialect used to parse the input expression (in the case that the
4594            input expression is a SQL string).
4595        **opts: other options to use to parse the input expressions (again, in the case
4596            that the input expression is a SQL string).
4597
4598    Returns:
4599        Select: the syntax tree for the SELECT statement.
4600    """
4601    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4604def update(
4605    table: str | Table,
4606    properties: dict,
4607    where: t.Optional[ExpOrStr] = None,
4608    from_: t.Optional[ExpOrStr] = None,
4609    dialect: DialectType = None,
4610    **opts,
4611) -> Update:
4612    """
4613    Creates an update statement.
4614
4615    Example:
4616        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4617        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4618
4619    Args:
4620        *properties: dictionary of properties to set which are
4621            auto converted to sql objects eg None -> NULL
4622        where: sql conditional parsed into a WHERE statement
4623        from_: sql statement parsed into a FROM statement
4624        dialect: the dialect used to parse the input expressions.
4625        **opts: other options to use to parse the input expressions.
4626
4627    Returns:
4628        Update: the syntax tree for the UPDATE statement.
4629    """
4630    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4631    update_expr.set(
4632        "expressions",
4633        [
4634            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4635            for k, v in properties.items()
4636        ],
4637    )
4638    if from_:
4639        update_expr.set(
4640            "from",
4641            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4642        )
4643    if isinstance(where, Condition):
4644        where = Where(this=where)
4645    if where:
4646        update_expr.set(
4647            "where",
4648            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4649        )
4650    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4653def delete(
4654    table: ExpOrStr,
4655    where: t.Optional[ExpOrStr] = None,
4656    returning: t.Optional[ExpOrStr] = None,
4657    dialect: DialectType = None,
4658    **opts,
4659) -> Delete:
4660    """
4661    Builds a delete statement.
4662
4663    Example:
4664        >>> delete("my_table", where="id > 1").sql()
4665        'DELETE FROM my_table WHERE id > 1'
4666
4667    Args:
4668        where: sql conditional parsed into a WHERE statement
4669        returning: sql conditional parsed into a RETURNING statement
4670        dialect: the dialect used to parse the input expressions.
4671        **opts: other options to use to parse the input expressions.
4672
4673    Returns:
4674        Delete: the syntax tree for the DELETE statement.
4675    """
4676    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4677    if where:
4678        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4679    if returning:
4680        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4681    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition( expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Condition:
4684def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4685    """
4686    Initialize a logical condition expression.
4687
4688    Example:
4689        >>> condition("x=1").sql()
4690        'x = 1'
4691
4692        This is helpful for composing larger logical syntax trees:
4693        >>> where = condition("x=1")
4694        >>> where = where.and_("y=1")
4695        >>> Select().from_("tbl").select("*").where(where).sql()
4696        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4697
4698    Args:
4699        *expression (str | Expression): the SQL code string to parse.
4700            If an Expression instance is passed, this is used as-is.
4701        dialect (str): the dialect used to parse the input expression (in the case that the
4702            input expression is a SQL string).
4703        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4704        **opts: other options to use to parse the input expressions (again, in the case
4705            that the input expression is a SQL string).
4706
4707    Returns:
4708        Condition: the expression
4709    """
4710    return maybe_parse(  # type: ignore
4711        expression,
4712        into=Condition,
4713        dialect=dialect,
4714        copy=copy,
4715        **opts,
4716    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy (bool): Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, copy=True, **opts) -> sqlglot.expressions.And:
4719def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4720    """
4721    Combine multiple conditions with an AND logical operator.
4722
4723    Example:
4724        >>> and_("x=1", and_("y=1", "z=1")).sql()
4725        'x = 1 AND (y = 1 AND z = 1)'
4726
4727    Args:
4728        *expressions (str | Expression): the SQL code strings to parse.
4729            If an Expression instance is passed, this is used as-is.
4730        dialect (str): the dialect used to parse the input expression.
4731        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4732        **opts: other options to use to parse the input expressions.
4733
4734    Returns:
4735        And: the new condition
4736    """
4737    return _combine(expressions, And, dialect, copy=copy, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, copy=True, **opts) -> sqlglot.expressions.Or:
4740def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4741    """
4742    Combine multiple conditions with an OR logical operator.
4743
4744    Example:
4745        >>> or_("x=1", or_("y=1", "z=1")).sql()
4746        'x = 1 OR (y = 1 OR z = 1)'
4747
4748    Args:
4749        *expressions (str | Expression): the SQL code strings to parse.
4750            If an Expression instance is passed, this is used as-is.
4751        dialect (str): the dialect used to parse the input expression.
4752        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4753        **opts: other options to use to parse the input expressions.
4754
4755    Returns:
4756        Or: the new condition
4757    """
4758    return _combine(expressions, Or, dialect, copy=copy, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Not:
4761def not_(expression, dialect=None, copy=True, **opts) -> Not:
4762    """
4763    Wrap a condition with a NOT operator.
4764
4765    Example:
4766        >>> not_("this_suit='black'").sql()
4767        "NOT this_suit = 'black'"
4768
4769    Args:
4770        expression (str | Expression): the SQL code strings to parse.
4771            If an Expression instance is passed, this is used as-is.
4772        dialect (str): the dialect used to parse the input expression.
4773        **opts: other options to use to parse the input expressions.
4774
4775    Returns:
4776        Not: the new condition
4777    """
4778    this = condition(
4779        expression,
4780        dialect=dialect,
4781        copy=copy,
4782        **opts,
4783    )
4784    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression, copy=True) -> sqlglot.expressions.Paren:
4787def paren(expression, copy=True) -> Paren:
4788    return Paren(this=_maybe_copy(expression, copy))
def to_identifier(name, quoted=None):
4804def to_identifier(name, quoted=None):
4805    """Builds an identifier.
4806
4807    Args:
4808        name: The name to turn into an identifier.
4809        quoted: Whether or not force quote the identifier.
4810
4811    Returns:
4812        The identifier ast node.
4813    """
4814
4815    if name is None:
4816        return None
4817
4818    if isinstance(name, Identifier):
4819        identifier = name
4820    elif isinstance(name, str):
4821        identifier = Identifier(
4822            this=name,
4823            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4824        )
4825    else:
4826        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4827    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4833def to_interval(interval: str | Literal) -> Interval:
4834    """Builds an interval expression from a string like '1 day' or '5 months'."""
4835    if isinstance(interval, Literal):
4836        if not interval.is_string:
4837            raise ValueError("Invalid interval string.")
4838
4839        interval = interval.this
4840
4841    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4842
4843    if not interval_parts:
4844        raise ValueError("Invalid interval string.")
4845
4846    return Interval(
4847        this=Literal.string(interval_parts.group(1)),
4848        unit=Var(this=interval_parts.group(2)),
4849    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4862def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4863    """
4864    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4865    If a table is passed in then that table is returned.
4866
4867    Args:
4868        sql_path: a `[catalog].[schema].[table]` string.
4869
4870    Returns:
4871        A table expression.
4872    """
4873    if sql_path is None or isinstance(sql_path, Table):
4874        return sql_path
4875    if not isinstance(sql_path, str):
4876        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4877
4878    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4879    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4882def to_column(sql_path: str | Column, **kwargs) -> Column:
4883    """
4884    Create a column from a `[table].[column]` sql path. Schema is optional.
4885
4886    If a column is passed in then that column is returned.
4887
4888    Args:
4889        sql_path: `[table].[column]` string
4890    Returns:
4891        Table: A column expression
4892    """
4893    if sql_path is None or isinstance(sql_path, Column):
4894        return sql_path
4895    if not isinstance(sql_path, str):
4896        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4897    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4900def alias_(
4901    expression: ExpOrStr,
4902    alias: str | Identifier,
4903    table: bool | t.Sequence[str | Identifier] = False,
4904    quoted: t.Optional[bool] = None,
4905    dialect: DialectType = None,
4906    **opts,
4907):
4908    """Create an Alias expression.
4909
4910    Example:
4911        >>> alias_('foo', 'bar').sql()
4912        'foo AS bar'
4913
4914        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4915        '(SELECT 1, 2) AS bar(a, b)'
4916
4917    Args:
4918        expression: the SQL code strings to parse.
4919            If an Expression instance is passed, this is used as-is.
4920        alias: the alias name to use. If the name has
4921            special characters it is quoted.
4922        table: Whether or not to create a table alias, can also be a list of columns.
4923        quoted: whether or not to quote the alias
4924        dialect: the dialect used to parse the input expression.
4925        **opts: other options to use to parse the input expressions.
4926
4927    Returns:
4928        Alias: the aliased expression
4929    """
4930    exp = maybe_parse(expression, dialect=dialect, **opts)
4931    alias = to_identifier(alias, quoted=quoted)
4932
4933    if table:
4934        table_alias = TableAlias(this=alias)
4935
4936        exp = exp.copy() if isinstance(expression, Expression) else exp
4937        exp.set("alias", table_alias)
4938
4939        if not isinstance(table, bool):
4940            for column in table:
4941                table_alias.append("columns", to_identifier(column, quoted=quoted))
4942
4943        return exp
4944
4945    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4946    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4947    # for the complete Window expression.
4948    #
4949    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4950
4951    if "alias" in exp.arg_types and not isinstance(exp, Window):
4952        exp = exp.copy()
4953        exp.set("alias", alias)
4954        return exp
4955    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4958def subquery(expression, alias=None, dialect=None, **opts):
4959    """
4960    Build a subquery expression.
4961
4962    Example:
4963        >>> subquery('select x from tbl', 'bar').select('x').sql()
4964        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4965
4966    Args:
4967        expression (str | Expression): the SQL code strings to parse.
4968            If an Expression instance is passed, this is used as-is.
4969        alias (str | Expression): the alias name to use.
4970        dialect (str): the dialect used to parse the input expression.
4971        **opts: other options to use to parse the input expressions.
4972
4973    Returns:
4974        Select: a new select with the subquery expression included
4975    """
4976
4977    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4978    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4981def column(
4982    col: str | Identifier,
4983    table: t.Optional[str | Identifier] = None,
4984    db: t.Optional[str | Identifier] = None,
4985    catalog: t.Optional[str | Identifier] = None,
4986    quoted: t.Optional[bool] = None,
4987) -> Column:
4988    """
4989    Build a Column.
4990
4991    Args:
4992        col: column name
4993        table: table name
4994        db: db name
4995        catalog: catalog name
4996        quoted: whether or not to force quote each part
4997    Returns:
4998        Column: column instance
4999    """
5000    return Column(
5001        this=to_identifier(col, quoted=quoted),
5002        table=to_identifier(table, quoted=quoted),
5003        db=to_identifier(db, quoted=quoted),
5004        catalog=to_identifier(catalog, quoted=quoted),
5005    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5008def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5009    """Cast an expression to a data type.
5010
5011    Example:
5012        >>> cast('x + 1', 'int').sql()
5013        'CAST(x + 1 AS INT)'
5014
5015    Args:
5016        expression: The expression to cast.
5017        to: The datatype to cast to.
5018
5019    Returns:
5020        A cast node.
5021    """
5022    expression = maybe_parse(expression, **opts)
5023    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
5026def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5027    """Build a Table.
5028
5029    Args:
5030        table (str | Expression): column name
5031        db (str | Expression): db name
5032        catalog (str | Expression): catalog name
5033
5034    Returns:
5035        Table: table instance
5036    """
5037    return Table(
5038        this=to_identifier(table, quoted=quoted),
5039        db=to_identifier(db, quoted=quoted),
5040        catalog=to_identifier(catalog, quoted=quoted),
5041        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5042    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5045def values(
5046    values: t.Iterable[t.Tuple[t.Any, ...]],
5047    alias: t.Optional[str] = None,
5048    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5049) -> Values:
5050    """Build VALUES statement.
5051
5052    Example:
5053        >>> values([(1, '2')]).sql()
5054        "VALUES (1, '2')"
5055
5056    Args:
5057        values: values statements that will be converted to SQL
5058        alias: optional alias
5059        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5060         If either are provided then an alias is also required.
5061
5062    Returns:
5063        Values: the Values expression object
5064    """
5065    if columns and not alias:
5066        raise ValueError("Alias is required when providing columns")
5067
5068    return Values(
5069        expressions=[convert(tup) for tup in values],
5070        alias=(
5071            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5072            if columns
5073            else (TableAlias(this=to_identifier(alias)) if alias else None)
5074        ),
5075    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5078def var(name: t.Optional[ExpOrStr]) -> Var:
5079    """Build a SQL variable.
5080
5081    Example:
5082        >>> repr(var('x'))
5083        '(VAR this: x)'
5084
5085        >>> repr(var(column('x', table='y')))
5086        '(VAR this: x)'
5087
5088    Args:
5089        name: The name of the var or an expression who's name will become the var.
5090
5091    Returns:
5092        The new variable node.
5093    """
5094    if not name:
5095        raise ValueError("Cannot convert empty name into var.")
5096
5097    if isinstance(name, Expression):
5098        name = name.name
5099    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5102def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5103    """Build ALTER TABLE... RENAME... expression
5104
5105    Args:
5106        old_name: The old name of the table
5107        new_name: The new name of the table
5108
5109    Returns:
5110        Alter table expression
5111    """
5112    old_table = to_table(old_name)
5113    new_table = to_table(new_name)
5114    return AlterTable(
5115        this=old_table,
5116        actions=[
5117            RenameTable(this=new_table),
5118        ],
5119    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5122def convert(value: t.Any, copy: bool = False) -> Expression:
5123    """Convert a python value into an expression object.
5124
5125    Raises an error if a conversion is not possible.
5126
5127    Args:
5128        value: A python object.
5129        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5130
5131    Returns:
5132        Expression: the equivalent expression object.
5133    """
5134    if isinstance(value, Expression):
5135        return _maybe_copy(value, copy)
5136    if isinstance(value, str):
5137        return Literal.string(value)
5138    if isinstance(value, bool):
5139        return Boolean(this=value)
5140    if value is None or (isinstance(value, float) and math.isnan(value)):
5141        return NULL
5142    if isinstance(value, numbers.Number):
5143        return Literal.number(value)
5144    if isinstance(value, datetime.datetime):
5145        datetime_literal = Literal.string(
5146            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5147        )
5148        return TimeStrToTime(this=datetime_literal)
5149    if isinstance(value, datetime.date):
5150        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5151        return DateStrToDate(this=date_literal)
5152    if isinstance(value, tuple):
5153        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5154    if isinstance(value, list):
5155        return Array(expressions=[convert(v, copy=copy) for v in value])
5156    if isinstance(value, dict):
5157        return Map(
5158            keys=[convert(k, copy=copy) for k in value],
5159            values=[convert(v, copy=copy) for v in value.values()],
5160        )
5161    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children(expression, fun, *args, **kwargs):
5164def replace_children(expression, fun, *args, **kwargs):
5165    """
5166    Replace children of an expression with the result of a lambda fun(child) -> exp.
5167    """
5168    for k, v in expression.args.items():
5169        is_list_arg = type(v) is list
5170
5171        child_nodes = v if is_list_arg else [v]
5172        new_child_nodes = []
5173
5174        for cn in child_nodes:
5175            if isinstance(cn, Expression):
5176                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5177                    new_child_nodes.append(child_node)
5178                    child_node.parent = expression
5179                    child_node.arg_key = k
5180            else:
5181                new_child_nodes.append(cn)
5182
5183        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
5186def column_table_names(expression):
5187    """
5188    Return all table names referenced through columns in an expression.
5189
5190    Example:
5191        >>> import sqlglot
5192        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5193        ['c', 'a']
5194
5195    Args:
5196        expression (sqlglot.Expression): expression to find table names
5197
5198    Returns:
5199        list: A list of unique names
5200    """
5201    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
5204def table_name(table) -> str:
5205    """Get the full name of a table as a string.
5206
5207    Args:
5208        table (exp.Table | str): table expression node or string.
5209
5210    Examples:
5211        >>> from sqlglot import exp, parse_one
5212        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5213        'a.b.c'
5214
5215    Returns:
5216        The table name.
5217    """
5218
5219    table = maybe_parse(table, into=Table)
5220
5221    if not table:
5222        raise ValueError(f"Cannot parse {table}")
5223
5224    return ".".join(
5225        part
5226        for part in (
5227            table.text("catalog"),
5228            table.text("db"),
5229            table.name,
5230        )
5231        if part
5232    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
5235def replace_tables(expression, mapping):
5236    """Replace all tables in expression according to the mapping.
5237
5238    Args:
5239        expression (sqlglot.Expression): expression node to be transformed and replaced.
5240        mapping (Dict[str, str]): mapping of table names.
5241
5242    Examples:
5243        >>> from sqlglot import exp, parse_one
5244        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5245        'SELECT * FROM c'
5246
5247    Returns:
5248        The mapped expression.
5249    """
5250
5251    def _replace_tables(node):
5252        if isinstance(node, Table):
5253            new_name = mapping.get(table_name(node))
5254            if new_name:
5255                return to_table(
5256                    new_name,
5257                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5258                )
5259        return node
5260
5261    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
5264def replace_placeholders(expression, *args, **kwargs):
5265    """Replace placeholders in an expression.
5266
5267    Args:
5268        expression (sqlglot.Expression): expression node to be transformed and replaced.
5269        args: positional names that will substitute unnamed placeholders in the given order.
5270        kwargs: keyword arguments that will substitute named placeholders.
5271
5272    Examples:
5273        >>> from sqlglot import exp, parse_one
5274        >>> replace_placeholders(
5275        ...     parse_one("select * from :tbl where ? = ?"),
5276        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5277        ... ).sql()
5278        "SELECT * FROM foo WHERE str_col = 'b'"
5279
5280    Returns:
5281        The mapped expression.
5282    """
5283
5284    def _replace_placeholders(node, args, **kwargs):
5285        if isinstance(node, Placeholder):
5286            if node.name:
5287                new_name = kwargs.get(node.name)
5288                if new_name:
5289                    return convert(new_name)
5290            else:
5291                try:
5292                    return convert(next(args))
5293                except StopIteration:
5294                    pass
5295        return node
5296
5297    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5300def expand(
5301    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5302) -> Expression:
5303    """Transforms an expression by expanding all referenced sources into subqueries.
5304
5305    Examples:
5306        >>> from sqlglot import parse_one
5307        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5308        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5309
5310        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5311        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5312
5313    Args:
5314        expression: The expression to expand.
5315        sources: A dictionary of name to Subqueryables.
5316        copy: Whether or not to copy the expression during transformation. Defaults to True.
5317
5318    Returns:
5319        The transformed expression.
5320    """
5321
5322    def _expand(node: Expression):
5323        if isinstance(node, Table):
5324            name = table_name(node)
5325            source = sources.get(name)
5326            if source:
5327                subquery = source.subquery(node.alias or name)
5328                subquery.comments = [f"source: {name}"]
5329                return subquery.transform(_expand, copy=False)
5330        return node
5331
5332    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5335def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5336    """
5337    Returns a Func expression.
5338
5339    Examples:
5340        >>> func("abs", 5).sql()
5341        'ABS(5)'
5342
5343        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5344        'CAST(5 AS DOUBLE)'
5345
5346    Args:
5347        name: the name of the function to build.
5348        args: the args used to instantiate the function of interest.
5349        dialect: the source dialect.
5350        kwargs: the kwargs used to instantiate the function of interest.
5351
5352    Note:
5353        The arguments `args` and `kwargs` are mutually exclusive.
5354
5355    Returns:
5356        An instance of the function of interest, or an anonymous function, if `name` doesn't
5357        correspond to an existing `sqlglot.expressions.Func` class.
5358    """
5359    if args and kwargs:
5360        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5361
5362    from sqlglot.dialects.dialect import Dialect
5363
5364    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5365    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5366
5367    parser = Dialect.get_or_raise(dialect)().parser()
5368    from_args_list = parser.FUNCTIONS.get(name.upper())
5369
5370    if from_args_list:
5371        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5372    else:
5373        kwargs = kwargs or {"expressions": converted}
5374        function = Anonymous(this=name, **kwargs)
5375
5376    for error_message in function.error_messages(converted):
5377        raise ValueError(error_message)
5378
5379    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5382def true():
5383    """
5384    Returns a true Boolean expression.
5385    """
5386    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5389def false():
5390    """
5391    Returns a false Boolean expression.
5392    """
5393    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5396def null():
5397    """
5398    Returns a Null expression.
5399    """
5400    return Null()

Returns a Null expression.